首页 > 解决方案 > Python Edge 驱动程序 Web 自动化帮助 - 找不到 Xpath

问题描述

检查 Youtube 页面元素 我是 Python 新手,我正在学习如何自动化网页。我基于使用检查元素选项卡下的不同定位器来驱动我的代码的基础知识。

我已经编写了一些基本代码来跳过 youtube 广告,但是我一直在寻找正确的页面元素以同意 Youtube 中的隐私政策弹出框。我已经使用 ChroPath 来尝试找到页面的 xpath,但似乎没有。我无法找到任何其他页面元素,我想知道是否有人对如何自动单击“我同意”按钮有任何想法?

蟒蛇代码:

from msedge.selenium_tools import Edge, EdgeOptions

options = EdgeOptions()
options.use_chromium = True
driver = Edge(options=options)

driver.get('http://www.youtube.com')

def agree():
    while True:
        try:
            driver.find_element_by_xpath('/html/body/ytd-app/ytd-popup-container/paper-dialog/yt-upsell-dialog-renderer/div/div[3]/div[1]/yt-button-renderer/a/paper-button').click()
            driver.find_elements_by_xpath('.<span class="RveJvd snByac">I agree</span>').click()
        except:
            continue

if __name__ == '__main__':
    agree()

Youtube 检查元素截图如下:

标签: pythonpycharmmicrosoft-edge

解决方案


我不知道您代码中的 xpath 是否正确,因为我看不到页面的整个 html 结构。但是您可以在 Edge 中使用 F12 开发工具来查找 xpath 并检查您找到的 xpath 是否正确:

  1. 打开要自动化的页面并在 Edge 中打开 F12 开发工具。
  2. 使用Ctrl+Shift+C并单击要定位的元素并找到该元素的 html 代码。
  3. 右键单击 html 代码并选择Copy -> Copy XPath
  4. 然后你可以尝试使用你复制的xpath。

在此处输入图像描述

此外,如果找到任何元素,find_elements_by_xpath(xpath)将返回一个包含元素的列表。我认为您需要指定要单击列表中的哪一个元素。您需要像这样传入元素列表的值编号[x],例如:

driver.find_elements_by_xpath('.<span class="RveJvd snByac">I agree</span>')[0].click()

推荐阅读