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

Python/Selenium - Getting the element after an element

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

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

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)