在Python中查找Selenium元素时遇到问题

2024-05-18 19:55:07 发布

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

我一直在努力收集Youtube游戏的直播频道/观众名单。我使用selenium和Python来强制网站向下滚动页面,以便加载超过11个频道。作为参考,this是我正在处理的网页。在

我已经找到了我想要的数据的位置,但是我正在努力让selenium去那里。我遇到麻烦的部分如下:

<div class="style-scope ytg-gaming-video-renderer" id="video-metadata"><span class="title ellipsis-2 style-scope ytg-gaming-video-renderer"><ytg-nav-endpoint class="style-scope ytg-gaming-video-renderer x-scope ytg-nav-endpoint-2"><a href="/watch?v=FFKSD1HHrdA" tabindex="0" class="style-scope ytg-nav-endpoint" target="_blank">
              Live met Bo3
            </a></ytg-nav-endpoint></span>
    <div class="channel-info small layout horizontal center style-scope ytg-gaming-video-renderer">
        <ytg-owner-badges class="style-scope ytg-gaming-video-renderer x-scope ytg-owner-badges-0">
            <template class="style-scope ytg-owner-badges" is="dom-repeat"></template>
        </ytg-owner-badges>
        <ytg-formatted-string class="style-scope ytg-gaming-video-renderer">
            <ytg-nav-endpoint class="style-scope ytg-formatted-string x-scope ytg-nav-endpoint-2"><a href="/channel/UCD8Q9V5wgo8o0XGfUqsRrDQ" tabindex="0" class="style-scope ytg-nav-endpoint" target="_blank">Rico Eeman</a>
            </ytg-nav-endpoint>
        </ytg-formatted-string>
    </div><span class="ellipsis-1 small style-scope ytg-gaming-video-renderer" id="video-viewership-info" hidden=""></span>
    <div id="metadata-badges" class="small style-scope ytg-gaming-video-renderer">
        <ytg-live-badge-renderer class="style-scope ytg-gaming-video-renderer x-scope ytg-live-badge-renderer-1">
            <template class="style-scope ytg-live-badge-renderer" is="dom-if"></template>

            <span aria-label="" class="text layout horizontal center style-scope ytg-live-badge-renderer">4 watching</span>
            <template class="style-scope ytg-live-badge-renderer" is="dom-if"></template>
        </ytg-live-badge-renderer>
    </div>
</div>

目前,我正在尝试:

^{pr2}$

但是,我在获取通道名时遇到了困难(在本例中,'Rico Eeman',它位于第一个嵌套的div标记下)。因为它是一个复合类名,我无法按类名找到元素,并且尝试以下XPath无效:

name = meta_data.find_element_by_xpath('/div[@class="channel-info small layout horizontal center style-scope ytg-gaming-video-renderer"]/ytg-formatted-string'

name = meta_data.find_element_by_xpath('/div[1])

它们都会引发元素未找到错误。我真的不知道该怎么办。有人有可行的解决方案吗?在



Tags: badgedivlivestylevideotemplateendpointclass
2条回答

name id不在<ytg-formatted-string>标记中,而是在它的一个后代中。试试看

meta_data.find_element_by_css_selector('.style-scope.ytg-formatted-string.x-scope.ytg-nav-endpoint-2 > a')

或使用xpath

^{pr2}$

这将获得所有名称,即使您的xpath使用video-metadata无法获得所有名称,每个用户的id都会重复,因此您需要查找元素并迭代返回的元素:

names = dr.find_elements_by_css_selector("a.style-scope.ytg-nav-endpoint[href^='/channel/']")
print([name.get_attribute("text") for name in names])

这给了你:

^{pr2}$

相关问题 更多 >

    热门问题