为什么Selenium在某些站点上找不到元素?

2024-05-15 21:40:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python版本的Selenium在一个中国网站上捕获评论

该网站是https://v.douyu.com/show/kDe0W2q5bB2MA4Bz

我想找到这个span元素。这在中文里叫做“弹幕列表".

enter image description here

我尝试了绝对路径,如:

driver.find_elements_by_xpath('/body/demand-video-app/main/div[2]/demand-video-helper//div/div[1]/a[3]/span')

但是它返回的是NoSuchElementException。我只是觉得这个网站可能有一个保护机制。但是,我对硒了解不多,我想寻求帮助。提前谢谢


Tags: https版本divcom元素网站videoselenium
1条回答
网友
1楼 · 发布于 2024-05-15 21:40:21

我猜您使用Selenium是因为requests无法捕获值

如果这不是你想做的,不要读我的答案

因为你是requests.get(url='https://v.douyu.com/show/kDe0W2q5bB2MA4Bz')

您需要在F12 Network上找到数据ApiUrl的源

事实上,他的信息来源是

https://v.douyu.com/wgapi/vod/center/getBarrageListByPage+parameter

https://v.douyu.com/wgapi/vod/center/getBarrageListByPage?vid=kDe0W2q5bB2MA4Bz&forward=0&offset=-1

虽然我不能帮你解决硒的问题

但是我将使用以下方法来获取数据

import requests

url = 'https://v.douyu.com/wgapi/vod/center/getBarrageListByPage?vid=kDe0W2q5bB2MA4Bz&forward=0&offset=-1'
headers = {'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'}
res = requests.get(url=url, headers=headers).json()
print(res)
for i in res['data']['list']:
    print(i)

获取所有数据

import requests

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}
url = 'https://v.douyu.com/wgapi/vod/center/getBarrageListByPage?vid=kDe0W2q5bB2MA4Bz&forward=0&offset=-1'
while True:
    res = requests.get(url=url, headers=headers).json()
    next_json = res['data']['pre']
    if next_json == -1:
        break
    for i in res['data']['list']:
        print(i)
    url = f'https://v.douyu.com/wgapi/vod/center/getBarrageListByPage?vid=kDe0W2q5bB2MA4Bz&forward=0&offset={next_json}'

相关问题 更多 >