python - 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 检查元素截图如下:
解决方案
我不知道您代码中的 xpath 是否正确,因为我看不到页面的整个 html 结构。但是您可以在 Edge 中使用 F12 开发工具来查找 xpath 并检查您找到的 xpath 是否正确:
- 打开要自动化的页面并在 Edge 中打开 F12 开发工具。
- 使用Ctrl+Shift+C并单击要定位的元素并找到该元素的 html 代码。
- 右键单击 html 代码并选择Copy -> Copy XPath。
- 然后你可以尝试使用你复制的xpath。
此外,如果找到任何元素,find_elements_by_xpath(xpath)
将返回一个包含元素的列表。我认为您需要指定要单击列表中的哪一个元素。您需要像这样传入元素列表的值编号[x]
,例如:
driver.find_elements_by_xpath('.<span class="RveJvd snByac">I agree</span>')[0].click()
推荐阅读
- javascript - 如何在 Javascript 中循环遍历嵌套对象并随后将值添加到 HTML 表格单元格?
- typescript - 使用 yarn/npm 链接时导出类型和枚举失败
- javascript - 如何通过浏览器(Chrome)在运行时引发 javascript 错误?
- r - 使用 dbplyr 将字符串拆分为行
- api - 为什么在使用 Mailgun API 时出现 Mailgun Magnificent API 错误
- c# - 如何读取属性参数和值(类属性或方法属性)?
- c++ - 编译时从 input.txt 在 VS 代码终端中自动输入
- image - 使用 Chrome 无法在我的 html 中加载在线图片
- javascript - 从markdown中提取第一个p和h1标签内容
- user-interface - 将 Xamarin Forms 4.8 更新到 5 后 Xamarin UWP 项目在应用程序设计器页面中因未处理的异常而崩溃