原帖:fake-useragent库没正确发挥作用出现索引超出范围问题
代码重现
from fake_useragent import UserAgent
import random
ua = UserAgent(path="") # 如果下载在默认位置,无须强调路径。
headers = {'User-Agent': ua.random}
报错重现
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
关键部分(辨识):ua = UserAgent() 后进入fake.py utils.py......报错html = ......至IndexError。
解决方案
①From Github pull request #110. 就是找到fake_useragent/utils.py source code. 然后Go to line 99, change the w3 to ws:
html = html.split('<table class="w3-table-all notranslate">')[1]
↓↓↓
html = html.split('<table class="ws-table-all notranslate">')[1]
②更新版本
原因分析暂时没深究,可看看原帖提供的github是否有说 为啥米
时隔N月后,我回来了。首先祝福大家兔年吉祥,前途似锦,身体健康!
忙于秋招,如今闲下来,重拾爱好。祝好,望列位不负热爱!