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

  • 相关阅读:
    为什么一看编程技术文章就这么兴奋呢?
    今天弄会了如何使用VB6使用AutoCAD提供的dll操作AutoCAD了
    简单工厂模式没想像中的难啊
    Linq本质论,C#3.0的特性。写的太好了!收藏!
    struct和class的区别
    饿了
    解决Eclipse 3.3+lomboz无法启动的问题
    IE8通过Acid2了
    Linux档案/目录 权限及修改
    Linux 初识man、info
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/12893753.html
Copyright © 2011-2022 走看看