修改urllib2源代码,定制User-Agent,一劳永逸
我经常用到urllib2这个库,基本上每次都要添加 User-Agent 为一个模拟浏览器的值。
突然想到,能不能直接修改源代码,添加 User-Agent 的值。
google 到 https://docs.python.org/2/library/urllib2.html
其中有解释说:
headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. This is often used to “spoof” the User-Agent header, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127Firefox/2.0.0.11", while urllib2‘s default user agent string is "Python-urllib/2.6" (on Python 2.6).
User-Agent是有默认值的,而且与版本有关。
定位urllib2.py
然后直接vim中查找 Python-urllib/
在310 行找到了,默认是
client_version = "Python-urllib/%s" % __version__
其中的 __version__ 就是python的版本号,代码在120 行,我修改的时候直接忽略了。
修改后:
client_version = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36'
很简单吧。
测试一下