python学习心得(三):fake_useragent模块

为了爬虫需要,经常要构造头部代理,而python的fake_useragent模块提供了这个功能,不需要每次都自己写一堆代理的代码了。

首先,fake_useragent在python3.5的版本上安装是有问题的,我是升级到3.7的版本之后再回去做了橡皮擦的课程练习,在橡皮擦老师的课程代码里面直接使用无参函数构造对象

from fake_useragent import UserAgent
ua=UserAgent()

实测下来会报错,搜索了一遍发现一般要禁用cache,也就是用下面的带参构造来创建对象

ua = UserAgent(use_cache_server=False)

但是换了一个项目后,发现构造伪代理又出错了

raise FakeUserAgentError('Maximum amount of retries reached')
fake_useragent.errors.FakeUserAgentError: Maximum amount of retries reached

这次决定彻底找到问题
百度过各种带参的构造方法

#禁服务器缓存
ua = UserAgent(use_cache_server=False)
#无效

#不缓存数据:
ua = UserAgent(cache=False)
#无效

#忽略ssl验证:
ua = UserAgent(verify_ssl=False)
#无效

下载一个代理数据集合 https://fake-useragent.herokuapp.com/browsers/0.1.11,并将数据包放在项目目录下,使用该数据包来构造对象

liufeng@ubuntu:~/python3demo/zhihu25$ wget https://fake-useragent.herokuapp.com/browsers/0.1.11
--2019-03-15 19:53:05--  https://fake-useragent.herokuapp.com/browsers/0.1.11
Resolving fake-useragent.herokuapp.com (fake-useragent.herokuapp.com)... 52.30.29.105, 54.76.59.126, 54.76.75.251, ...
Connecting to fake-useragent.herokuapp.com (fake-useragent.herokuapp.com)|52.30.29.105|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 42686 (42K) [application/json]
Saving to:0.1.110.1.11               100%[======================>]  41.69K  76.9KB/s    in 0.5s

2019-03-15 19:53:09 (76.9 KB/s) -0.1.11’ saved [42686/42686]

liufeng@ubuntu:~/python3demo/zhihu25$ ls
0.1.11  zhihu.csv  zhihu.py  zhihu.py.bak
liufeng@ubuntu:~/python3demo/zhihu25$ mv 0.1.11 fake_useragent.json
liufeng@ubuntu:~/python3demo/zhihu25$ ls
fake_useragent.json  zhihu.csv  zhihu.py  zhihu.py.bak

使用的时候将该库所在的路径包含进去构造ua对象即可

location = os.getcwd() + '/fake_useragent.json'
ua = UserAgent(path=location)

当前如果禁用服务器cache的构造可以爬当前的网站,就没有必要再这么做了。

猜你喜欢

转载自blog.csdn.net/weixin_40983190/article/details/88593976