-
232024年4月
-
302024年3月
-
292024年2月
-
312024年1月
-
312023年12月
-
302023年11月
-
312023年10月
-
302023年9月
-
312023年8月
-
352023年7月
-
312023年6月
-
312023年5月
-
302023年4月
-
312023年3月
-
282023年2月
-
312023年1月
-
312022年12月
-
302022年11月
-
312022年10月
-
302022年9月
-
312022年8月
-
322022年7月
-
292022年6月
-
322022年5月
-
302022年4月
-
332022年3月
-
312022年2月
-
372022年1月
-
382021年12月
-
382021年11月
-
402021年10月
-
432021年9月
-
372021年8月
-
442021年7月
-
442021年6月
-
432021年5月
-
342021年4月
-
312021年3月
-
292021年2月
-
352021年1月
-
422020年12月
-
402020年11月
-
482020年10月
-
522020年9月
-
852020年8月
-
752020年7月
-
802020年6月
-
782020年5月
-
772020年4月
-
432020年3月
-
362020年2月
-
452020年1月
-
562019年12月
-
712019年11月
-
612019年10月
-
562019年9月
-
532019年8月
-
362019年7月
-
362019年6月
-
382019年5月
-
402019年4月
-
352019年3月
-
342019年2月
-
442019年1月
-
392018年12月
-
402018年11月
-
392018年10月
-
392018年9月
-
452018年8月
-
452018年7月
-
392018年6月
-
512018年5月
-
492018年4月
-
342018年3月
-
282018年2月
-
482018年1月
-
732017年12月
-
7292017年11月
-
7442017年10月
-
2892017年9月
-
12017年8月
很多网站都不喜欢被爬虫程序访问,但又没有办法完全禁止,于是就设置了一些反爬策略。比如User Agent,中文名为用户代理,简称UA。User Agent存放于Headers中,服务器就是通过查看Headers中的User Agent来判断是谁在访问。
通过不同的浏览器访问,会有不同的User Agent,如果爬虫不设置的话,很容易被识别出来,就会被限制访问。一般的做法是收集很多不同的User Agent,然后随机使用。
那么如何设置User Agent呢,其实是有两种方法(以python为例)的:
一、在创建Request对象的时候,填入headers参数(包含User Agent信息),这个Headers参数要求为字典。
from urllib import request
if __name__ == "__main__":
#以CSDN为例,CSDN不更改User Agent是无法访问的
url = 'http://www.csdn.net/'
head = {}
#写入User Agent信息
head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
#创建Request对象
req = request.Request(url, headers=head)
#传入创建好的Request对象
response = request.urlopen(req)
#读取响应信息并解码
html = response.read().decode('utf-8')
#打印信息
print(html)
二、在创建Request对象的时候不添加headers参数,在创建完成之后,使用add_header()的方法,添加headers。
from urllib import request
if __name__ == "__main__":
#以CSDN为例,CSDN不更改User Agent是无法访问的
url = 'http://www.csdn.net/'
#创建Request对象
req = request.Request(url)
#传入headers
req.add_header('User-Agent', 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19')
#传入创建好的Request对象
response = request.urlopen(req)
#读取响应信息并解码
html = response.read().decode('utf-8')
#打印信息
print(html)