zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    字节输入输出流
    数据库安全性
    数据库设计:三种范式
    (Java篇) 代理服务:Nginx ---》(1)介绍及安装
    (十七)微信小程序:全局优化
    (十六)微信小程序:电影详情页
    (十五)微信小程序:优化电影页面
    (十四)微信小程序:上拉加载 下拉刷新
    (十三)微信小程序:更多电影页面
    管理:会议纲要
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/12893753.html
Copyright © 2011-2022 走看看