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

问题描述 投票:0回答:1

我需要通过按右上角的“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找到了一个bandaid解决方案。但我试图真正理解如何实际解决这个问题。我不确定我的解决方案有什么错误:

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?

python selenium siblings
1个回答
1
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.