【问题标题】:Python Finding element by XPathPython 通过 XPath 查找元素
【发布时间】:2020-07-20 10:19:56
【问题描述】:

参考访问https://rabirius.me/2020/02/14/bird-watching/(不是我的网站)

您可能会在转发按钮附近看到一个赞按钮

我希望 python 点击​​它,但我收到一个错误提示

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div/div[2]/a"}

我写的代码是

for posts in open_links:
       bot.get(posts)
       sleep(4)
       bot.find_element_by_xpath('/html/body/div/div/div[2]/a').click()
       sleep(2)

like按钮的HTML是

<div class="wpl-button like">
            <a href="#" title="177 bloggers like this." class="like sd-button" rel="nofollow">
                <span>Like</span>
            </a>
        </div>

任何帮助将不胜感激

【问题讨论】:

标签: python html selenium google-chrome xpath


【解决方案1】:

页面上存在 iframe,因此您需要先切换到该 iframe,然后对元素进行操作,并且建议使用显式等待来等待元素出现在页面上。 你可以这样做:

for posts in open_links:
   bot.get(posts)
   driver.switch_to.frame(bot.find_element_by_tag_name('iframe'))
   like_element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class,'wpl-likebox')]//span[text()='Like']")))
   like_element.click()

您需要添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

【讨论】:

  • 当我使用你的代码时,我收到这条消息,WebDriverWait 未定义,Ec 未定义 By 未定义,请帮助
  • @ArjunBasandrai 您需要添加导入。我已经在我的ans中添加了这些,请选择更新后的ans
  • 我需要添加哪些导入 请解释一下,我对 Python 很陌生
  • @ArjunBasandrai 我已经更新了我的答案并补充说,在我的答案中,请检查我更新的答案
  • 我试图将它放在 for 循环内的 try 或 except 语句中,以查看它显示的内容 我收到此错误 ``` 消息:元素单击被拦截:元素
猜你喜欢
  • 2020-08-08
  • 2020-02-06
  • 2020-05-07
  • 2020-05-03
  • 2020-11-29
  • 2016-03-12
  • 2017-09-14
  • 2014-08-07
  • 1970-01-01
相关资源
最近更新 更多