Python Edge Driver Web Automation 帮助 - 找不到 Xpath

Python Edge Driver Web Automation Help - Cannot find Xpath

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

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

Python代码:

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 检查元素屏幕截图如下:

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

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

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

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

在检查页面元素时,我忽略了 iframe 元素。在做了一些挖掘之后,我发现我必须告诉 Selenium 驱动程序从主页切换到 iframe。我添加了以下代码,现在点击 'I Agree' 按钮是自动的:

frame_element = driver.find_element_by_id('iframe') driver.switch_to.frame(frame_element) agree2 = driver.find_element_by_xpath("/html/body/div/c-wiz/div[2]/div/div/div/div/div[2]/form/div/span/span").click() driver.switch_to.default_content()