用户代理
以优快云为例,优快云不更改User Agent是无法访问的,使用User Agent只是为了模拟人的点击访问 以便跳过爬虫检查
from urllib import request
if __name__ == '__main__':
url = 'http://www.youkuaiyun.com/'
head = {} #设置响应头
head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
req = request.Request(url,headers=head)
#传入创建好的Request对象
response = request.urlopen(req)
#读取响应信息并解码
html = response.read().decode('utf-8') print(html)
仅仅使用用户代理还不够,下面讲讲IP代理的使用,User Agent已经设置好了,但是还应该考虑一个问题,程序的运行速度是很快的,如果我们利用一个爬虫程序在网站爬取东西,一个固定IP的访问频率就会很高,这不符合人为操作的标准,因为人操作不可能在几ms内,进行如此频繁的访问。所以一些网站会设置一个IP访问频率的阈值,如果一个IP访问频率超过这个阈值,说明这个不是人在访问,而是一个爬虫程序。
if __name__ == '__main__':
url = 'http://www.whatismyip.com.tw/'
proxy = {'http':'116.213.98.6:8080'}
proxy_support = request.ProxyHandler(proxy)
opener = request.build_opener(proxy_support)
opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36')]
response = opener.open(url)
html = response.read().decode('utf-8')
print(html)
下面简单讲讲错误处理,urllib.error包括URLError和HTTPError两部分
下面代码讲述了两种error的混合使用情况
from urllib import request
from urllib import error
'''urllib.error 包括URLError和HTTPError '''
if __name__ == '__main__':
#一个不存在的链接
url = 'http://www.klkl002.com/'
req = request.Request(url)
try:
response = request.urlopen(req)
html = response.read().decode('utf-8')
print(html)
except error.URLError as e:
if hasattr(e,'code'):
print(e.code)
elif hasattr(e,'reason'):
print(e.reason)
# print(e.reason) #输出结果为getAddrInfo failed
#except error.HTTPError as e:
# print(e.code) #输出结果为404 NOT FOUND