Python 3 + Selenium : How to find this element by xpath?

标签 python html selenium xpath

https://www.facebook.com/friends/requests/?fcref=jwl&outgoing=1

我想在“已发送的好友请求”中点击“查看更多请求”

<div id="outgoing_reqs_pager_57b87e5793eb04682598549" class="clearfix mtm uiMorePager stat_elem _646 _52jv">
   <div>
       <a class="pam uiBoxLightblue _5cz uiMorePagerPrimary" role="button" href="#" ajaxify="/friends/requests/outgoing/more/?page=2&page_size=10&pager_id=outgoing_reqs_pager_57b87e5793eb04682598549" rel="async">See More Requests</a>
<span class="uiMorePagerLoader pam uiBoxLightblue _5cz">
   </div>
</div>

我使用了这段代码,但它不起作用。

driver.find_element_by_xpath("//*[contains(@id, 'outgoing_reqs_pager')]").click()

我收到错误:

Message: Element is not clickable at point (371.5, 23.166671752929688). Other element would receive the click:

<input aria-owns="js_8" class="_1frb" name="q" value="" autocomplete="off" placeholder="Search Facebook" role="combobox" aria-label="Search" aria-autocomplete="list" aria-expanded="false" aria-controls="js_5" aria-haspopup="true" type="text">

如何点击它?谢谢:)

最佳答案

实际上,您是通过使用部分 id 匹配来定位元素的,因此该 xpath 可能不唯一并返回多个元素。

find_element 始终通过匹配定位器返回第一个元素,可能是它返回被其他元素而不是所需元素覆盖的其他元素,这就是您遇到麻烦的原因。

在这里,您应该尝试使用 link_text 通过使用其文本来定位所需元素,如下所示:-

driver.find_element_by_link_text("See More Requests").click()

或使用 partial_link_text 如下:-

driver.find_element_by_partial_link_text("See More Requests").click()

Edited1 :- 如果您仍然遇到相同的异常,您需要先使用 exexute_script() 滚动以到达该元素,然后单击如下所示:-

link = driver.find_element_by_partial_link_text("See More Requests")

#now scroll to reach this link
driver.exexute_script("arguments[0].scrollIntoView()", link)

#now click on this link 
 link.click()

或者,如果您不想滚动,可以使用 exexute_script 单击而不滚动,如下所示:-

link = driver.find_element_by_partial_link_text("See More Requests")

#now perform click using javascript
driver.exexute_script("arguments[0].click()", link)

Edited2 :- 如果您想在 while 循环内单击此链接直到它出现,您需要实现 WebDriverWait 来等待它下次出现,如下所示:-

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)

# now find link
link = wait.until(EC.presence_of_element_located((By.LINK_TEXT, "See More Requests")))

#now perform click one of these above using java_script

关于Python 3 + Selenium : How to find this element by xpath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39056407/

相关文章:

python - py2exe 突然不再工作。没有名为 _view 的模块

python - 从 Python C 扩展函数返回参数时需要 INCREF?

python - 使用 Tensorflow 2.0 进行逻辑回归?

java - 无法使用 Selenium Webdriver 选择选项

java - WebDriver、ChromeDriver、Selenium 和 Jenkins 集成

python 3 ftp 目录到列表中

javascript - 如何使用 javascript 将 css-grid 元素放入网格容器中

jQuery load() 代码在 Google Chrome 中不起作用

javascript - 为什么 jQuery 对损坏的标记的解释与浏览器不同?

java - Selenium Webdriver 远程设置