Python/Selenium - 获取元素后面的元素

标签 python selenium siblings

我需要通过按右上角的“X”窗口来关闭网站本身的弹出窗口。这是我的代码的缩短的相关部分:

chromedriver = r'C:\Users\do\Desktop\chromedriver.exe'
browser = webdriver.Chrome(chromedriver)
url = 'Fake.com'

browser.get(url) 
browser.find_element_by_id('imgAttachmentsImg').click()
# I need to close out the window after this

问题在于“X”按钮本身没有唯一标识符。然而,弹出窗口本身确实有一个唯一的标识符。我只需要能够将其向下传递到 X 按钮。

页面信息:

1. V<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable" tabindex="-1" role="dialog" aria-describedby="attachmentsDialogOverview" aria-labelledby="ui-id-3" style="position: absolute; height: auto; width: auto; top: 239px; left: 102px; display: block;">
  2. <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
    3. <span id="ui-id-3" class="ui-dialog-title">Attachments</span>
   4. V<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">
       5. <span class="ui-button-icon-primary ui-icon ui-icon-closethick"</span>
       6. <span class="ui-button-text">close</span></button>

我刚开始使用 Python 和 Selenium。我从 VBA 转过来,但仍然不完全理解所有语法,所以我确实犯了错误!我确实通过让 sendkeys 按 Escape 找到了一个创可贴解决方案。但我正在尝试真正了解如何真正解决这个问题。我不确定我的解决方案犯了什么错误:

browser.find_element_by_xpath("//span[@id, 'ui-id-3']/following-sibling::button").click()

问题

  1. 为什么我的解决方案不起作用?

  2. 如何找到“ui-id-3”(第 3 行)并到达第 4 行的元素并单击它?

  3. 如何找到“ui-id-3”(第 3 行)并到达第 5 行上的元素并单击它? (只是为了让我知道如何跨多个元素移动)

<小时/>

我查看的相关链接:

Following-Sibling Python Selenium

Find next sibling element in Python Selenium?

Using XPath Selector 'following-sibling::text()' in Selenium (Python)

Python + Selenium WebDriver - Get div value if sibling contains string

What is the correct syntax for using a variable and following-sibling in Python Selenium?

最佳答案

xpath 有问题。这应该有效:

browser.find_element_by_xpath("//span[@id='ui-id-3']/following-sibling::button").click()

要获取其下方的范围,您可以使用:

browser.find_element_by_xpath("//span[@id='ui-id-3']/following-sibling::button/span")

顺便说一句,如果您更熟悉 CSS,等效路径是:

div#ui-id-3 > button
div#ui-id-3 > button span:nth-of-type(1)

关于Python/Selenium - 获取元素后面的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054985/

相关文章:

Python:从 3D 数组中提取 2D 数组

python - 使用 Selenium 在 div 中进行内容搜索的问题

jquery - 在分配给单击的元素时从同级中删除类不起作用

html - 如何在父元素和父元素的兄弟元素之上显示子元素?

python - 具有数千个选择的 Django 选择字段创建数以千计的数据库查询

python - 传递/返回 Cython Memoryviews 与 NumPy 数组

php - 收到 POST 请求后更新网页

python - 如何使用 Python 在 Selenium 中测试 Alert/Popup

javascript - getText() 不起作用

html - CSS 文本溢出取决于兄弟元素之外的剩余空间