随笔 - 214  文章 - 12  评论 - 40  阅读 - 38万

fake-useragent插件无法正常使用的问题

在进行Scrapy开发的时候,需要使用UA中间件,这里就采用了fake-useragent来随机获取浏览器的UA值,但貌似直接访问的话有异常:

File "/Users/mazhiyong/.virtualenvs/scrapy/lib/python3.7/site-packages/fake_useragent/utils.py", line 154, in load
    for item in get_browsers(verify_ssl=verify_ssl):
  File "/Users/mazhiyong/.virtualenvs/scrapy/lib/python3.7/site-packages/fake_useragent/utils.py", line 97, in get_browsers
    html = get(settings.BROWSERS_STATS_PAGE, verify_ssl=verify_ssl)
  File "/Users/mazhiyong/.virtualenvs/scrapy/lib/python3.7/site-packages/fake_useragent/utils.py", line 84, in get
    raise FakeUserAgentError('Maximum amount of retries reached')
fake_useragent.errors.FakeUserAgentError: Maximum amount of retries reached

貌似是网络访问问题。

 

综合资料,解决办法如下:

当然前提是先安装:

pip install fake-useragent

如果已经安装过,记得更新下:

pip install -U fake-useragent

然后手动下载UA的缓存文件,访问地址为;

https://fake-useragent.herokuapp.com/browsers/0.1.11

 目前最新版本是这个,以后可以根据版本不同再调整。

 

1、将下载的文件命名为: fake_useragent_0.1.11.json 并放入linux 或者 windows的临时目录。然后就可以正常使用fake-useragent了。

获取临时目录 方法:

>>> import tempfile
>>> tempfile.gettempdir()
'/tmp'

2、将fake_useragent_0.1.11.json存储到指定位置,然后使用fake-useragent的时候指定文件路径:

def get_header():
    location = os.getcwd() + '/fake_useragent.json'
    ua = fake_useragent.UserAgent(path=location)
    return ua.random

3、也可以自己直接解析fake_useragent_0.1.11.json文件使用。

 

使用示例:

>>> from fake_useragent import UserAgent
>>> ua = UserAgent(path="/Volumes/DATA/fake_useragent_0.1.11.json")
>>> ua.random
'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/24.0.1292.0 Safari/537.14'

 

参考文章:

https://pypi.org/project/fake-useragent/

https://blog.csdn.net/shaooping/article/details/90296667

https://www.cnblogs.com/rwxwsblog/p/10174940.html

posted on   麦克煎蛋  阅读(3050)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-05-15 FATAL ERROR: Tried to use mysqladmin in group......
2015-05-15 ABORT: Can't find command 'my_print_defaults'.
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示