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

5

我试着使用fake_useragent模块来实现以下功能:

from fake_useragent import UserAgent

ua = UserAgent()
print(ua.random)

但是当执行到这一行 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

我使用Linux并使用以下命令安装了该模块:pip3 install fake_useragent --upgrade

有解决此问题的解决方案吗?如果没有,是否有更好的模块可用?


错误来自于这个 html = html.split('<table class="w3-table-all notranslate">')[1] 而不是 fake_useragent - baduker
2
是的,这行代码来自于 fake_useragent 模块中的 utils.py 文件。 - Hadi Ayoub
2个回答

15

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

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

    html = html.split('<table class="w3-table-all notranslate">')[1]
#                                    ^^ change this

ws

    html = html.split('<table class="ws-table-all notranslate">')[1]
#                                    ^^ to this

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


† 要找到utils.py所在的fake_useragent目录,请运行以下代码:

import fake_useragent
print(fake_useragent.__file__)
例如,在我的Windows笔记本电脑上,这样打印出来
'C:\\Users\\mattdmo\\AppData\\Roaming\\Python\\Python310\\site-packages\\fake_useragent\\__init__.py'

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


这很好地解决了!首先,我尝试删除[1],但效果不佳。将w3更改为ws是有效的。非常感谢! - Hadi Ayoub
当我在我的服务器上通过pip3在docker中构建软件包时,我该如何更改这个? - Mathijs
@Mathijs,由于原始存储库的所有者似乎没有回应PR,最好的做法是fork存储库,应用修复程序,更新版本字符串,然后将pip3指向新存储库。 - MattDMo
在Windows中使用VS Code,我选择了Go => Go to file => 搜索Utils.py => 打开XXXX\Lib\site-packages\fake_useragent\utils.py。然后我编辑了这里提到的行,它就起作用了。 - GuitarViking

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接