fake_useragent 模块未正确连接 - IndexError:列表索引超出范围

Had*_*oub 6 python user-agent

我尝试将fake_useragent模块与此块一起使用

from fake_useragent import UserAgent

ua = UserAgent()
print(ua.random)
Run Code Online (Sandbox Code Playgroud)

但是当执行到这一行时ua = UserAgent(),它会抛出这个错误

Traceback (most recent call last):
  File "/home/hadi/Desktop/excel/gatewayform.py", line 191, in <module>
    gate = GateWay()
  File "/home/hadi/Desktop/excel/gatewayform.py", line 23, in __init__
    ua = UserAgent()
  File "/usr/local/lib/python3.9/dist-packages/fake_useragent/fake.py", line 69, in __init__
    self.load()
  File "/usr/local/lib/python3.9/dist-packages/fake_useragent/fake.py", line 75, in load
    self.data = load_cached(
  File "/usr/local/lib/python3.9/dist-packages/fake_useragent/utils.py", line 250, in load_cached
    update(path, use_cache_server=use_cache_server, verify_ssl=verify_ssl)
  File "/usr/local/lib/python3.9/dist-packages/fake_useragent/utils.py", line 245, in update
    write(path, load(use_cache_server=use_cache_server, verify_ssl=verify_ssl))
  File "/usr/local/lib/python3.9/dist-packages/fake_useragent/utils.py", line 178, in load
    raise exc
  File "/usr/local/lib/python3.9/dist-packages/fake_useragent/utils.py", line 154, in load
    for item in get_browsers(verify_ssl=verify_ssl):
  File "/usr/local/lib/python3.9/dist-packages/fake_useragent/utils.py", line 99, in get_browsers
    html = html.split('<table class="w3-table-all notranslate">')[1]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

我使用linux并且我已经使用这个命令安装了模块pip3 install fake_useragent --upgrade

这个问题有什么解决办法吗?如果没有,是否有更好的模块可以使用?

Mat*_*DMo 15

有一个解决方案,来自 Github pull request #110。基本上,您所需要做的就是更改fake_useragent/utils.py源代码一行中的一个字符。

\n

要在您的系统上执行此操作,请使用管理员权限在您喜欢的文本编辑器中打开/usr/local/lib/python3.9/dist-packages/fake_useragent/utils.py\xe2\x80\xa0。转到第 99 行,然后更改w3

\n
    html = html.split(\'<table class="w3-table-all notranslate">\')[1]\n#                                    ^^ change this\n
Run Code Online (Sandbox Code Playgroud)\n

ws

\n
    html = html.split(\'<table class="ws-table-all notranslate">\')[1]\n#                                    ^^ to this\n
Run Code Online (Sandbox Code Playgroud)\n

保存文件(具有管理员权限),重新启动 Python 会话,您的代码应该可以正常工作。

\n
\n

\xe2\x80\xa0 要查找fake_useragent所在目录utils.py,请运行以下代码:

\n
import fake_useragent\nprint(fake_useragent.__file__)\n
Run Code Online (Sandbox Code Playgroud)\n

例如,在我的 Windows 笔记本电脑上,此打印

\n
\'C:\\\\Users\\\\mattdmo\\\\AppData\\\\Roaming\\\\Python\\\\Python310\\\\site-packages\\\\fake_useragent\\\\__init__.py\'\n
Run Code Online (Sandbox Code Playgroud)\n

所以要打开的文件夹是C:\\Users\\mattdmo\\AppData\\Roaming\\Python\\Python310\\site-packages\\fake_useragent.

\n