参考学习:
一、urllib库介绍
urllib库,它是Python内置的HTTP请求库。它包含4个模块:
- request: HTTP请求模块, 可以用来模拟发送请求。
- error: 异常处理模块, 如果出现请求错误,我们可以捕获这些异常,然后进行重试或其他操作以保证程序不会意外终止。
- parse: url解析模块, 一个工具模块,提供了许多URL处理方法,比如拆分、解析、合并等。
- robotparser:robots解析模块, 主要是用来识别网站的robots.txt文件,然后判断哪些网站可以爬,哪些网站不可以爬,它其实用得比较少。
二、request模块
request模块主要功能:构造HTTP请求,利用它可以模拟浏览器的一个请求发起过程,
request模块同时还有:处理授权验证(authenticaton)、重定向(redirection)、浏览器Cookies以及其他内容。
1.urlopen方法
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
urlopen参数介绍:
- url用于请求URL
- data:GET请求不传,POST请求传
- timeout设置超时时间,单位为秒,意思就是如果请求超出了设置的这个时间,还没有得到响应,就会抛出异常。如果不指定该参数,就会使用全局默认时间。它支持HTTP、HTTPS、FTP请求。
- context必须是ssl.SSLContext类型,用来指定SSL设置。
- cafile指定CA证书
- capath指定CA证书的路径,这个在请求HTTPS链接时会有用。
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
print(data)
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())
2.Request方法
class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
Request参数介绍:
- url用于请求URL,这是必传参数,其他都是可选参数。
- data如果要传,必须传bytes(字节流)类型的。如果它是字典,可以先用urllib.parse模块里的urlencode()编码。
- headers是一个字典,它就是请求头,我们可以在构造请求时通过headers参数直接构造,也可以通过调用请求实例的add_header()方法添加。添加请求头最常用的用法就是通过修改User-Agent来伪装浏览器
- origin_req_host指的是请求方的host名称或者IP地址。
- unverifiable表示这个请求是否是无法验证的,默认是False,意思就是说用户没有足够权限来选择接收这个请求的结果。例如,我们请求一个HTML文档中的图片,但是我们没有自动抓取图像的权限,这时unverifiable的值就是True`。
- method是一个字符串,用来指示请求使用的方法,比如GET、POST和PUT等。
有很多网站为了防止程序爬虫爬网站造成网站瘫痪,会需要携带一些headers头部信息才能访问。
headers添加的两种方法如下:
方法1:
from urllib import request, parse
url = 'http://httpbin.org/post'
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Host': 'httpbin.org'
}
dict = {
'name': 'alex'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
方法2:
from urllib import request, parse
url = 'http://httpbin.org/post'
dict = {
'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
- Handler处理器
urllib.request模块里的BaseHandler类,它是所有其他Handler的父类。
常见Handler介绍:
- HTTPDefaultErrorHandler:用于处理HTTP响应错误,错误都会抛出HTTPError类型的异常。
- HTTPRedirectHandler:用于处理重定向。
- HTTPCookieProcessor:用于处理Cookies。
- ProxyHandler:用于设置代理,默认代理为空。
- HTTPPasswordMgr:用于管理密码,它维护了用户名和密码的表。
- HTTPBasicAuthHandler:用于管理认证,如果一个链接打开时需要认证,那么可以用它来解决认证问题。
3.代理ProxyHandler
Proxyhandler参数是一个字典,键名是协议类型(比如HTTP或者HTTPS等),键值是代理链接,可以添加多个代理。
然后,利用这个Handler及build_opener()方法构造一个Opener,之后发送请求即可。
from urllib.error import URLError
from urllib.request import ProxyHandler, build_opener
proxy_handler = ProxyHandler({
'http': 'http://127.0.0.1:9743',
'https': 'https://127.0.0.1:9743'
})
opener = build_opener(proxy_handler)
try:
response = opener.open('https://www.baidu.com')
print(response.read().decode('utf-8'))
except URLError as e:
print(e.reason)
3.cookies
cookie中保存中我们常见的登录信息,有时候爬取网站需要携带cookie信息访问,这里用到了http.cookijar,用于获取cookie以及存储cookie
# 从网页获取cookie,并逐行输出
import http.cookiejar, urllib.request
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
print(item.name+"="+item.value)
# 从网页获取cookie,保存为文件格式
filename = 'cookies.txt'
cookie = http.cookiejar.MozillaCookieJar(filename) # cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
PS:MozillaCookieJar是CookieJar的子类,LWPCookieJar与MozillaCookieJar均可读取、保存cookie,但格式不同
调用load()方法来读取本地的Cookies文件,获取到了Cookies的内容。
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookies.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))
三、error模块
from urllib import request, error
try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
print(e.reason)
四、parse模块
urlparse() urlunparse() urlsplit() urlunsplit() urljoin() urlencode() parse_qs() parse_qsl() quote() unquote()
五、robotparser模块
Robots协议也称作爬虫协议、机器人协议,它的全名叫作网络爬虫排除标准(Robots Exclusion Protocol),用来告诉爬虫和搜索引擎哪些页面可以抓取,哪些不可以抓取。它通常是一个叫作robots.txt的文本文件,
一般放在网站的根目录下。www.taobao.com/robots.txt
robotparser模块提供了一个类RobotFileParser,它可以根据某网站的robots.txt文件来判断一个爬取爬虫是否有权限来爬取这个网页。
urllib.robotparser.RobotFileParser(url='')
# set_url():用来设置robots.txt文件的链接。
# read():读取robots.txt文件并进行分析。
# parse():用来解析robots.txt文件。
# can_fetch():该方法传入两个参数,第一个是User-agent,第二个是要抓取的URL。
# mtime():返回的是上次抓取和分析robots.txt的时间。
# modified():将当前时间设置为上次抓取和分析robots.txt的时间。
from urllib.robotparser import RobotFileParser
rp = RobotFileParser()
rp.set_url('http://www.jianshu.com/robots.txt')
rp.read()
print(rp.can_fetch('*', 'http://www.jianshu.com/p/b67554025d7d'))
print(rp.can_fetch('*', "http://www.jianshu.com/search?q=python&page=1&type=collections"))