【问题标题】:Python Selenium Element clickPython Selenium 元素点击
【发布时间】:2021-02-27 23:55:55
【问题描述】:

凭借我在硒方面的初学者知识,我试图找到点击元素以打开链接。这些项目的链接没有href。如何点击正确的元素来打开链接。

我正在使用 python、selenium、chrome 网络驱动程序、BeautifulSoup。所有库都已更新。

下面是示例 html sn-p,其中有一个我需要使用 selenium 单击的标题。如果您需要更多 html 源代码,请告诉我。此代码来自仅“登录”的网站。

<h2> <!--For Verified item-->
  <a class="clickable" style="cursor:pointer;" onmousedown="open_item_detail('0000013', '0', false)" id="View item Detail" serial="0000013">
    Sample Item
  </a>
  <!--For unverified item-->
</h2>

【问题讨论】:

  • 分享链接和你要点击的项目名称

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

等待元素,然后通过正确的xpath查找。

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

driver = webdriver.Chrome('./chromedriver')
driver.get("https://yourpage.com")
elem = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//contains(a[text(),"Sample Item")]')))
elem.click()

【讨论】:

    【解决方案2】:

    点击元素需要诱导WebDriverWaitelement_to_be_clickable(),可以使用以下Locator Strategies之一:

    • 使用PARTIAL_LINK_TEXT

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Sample Item"))).click()
      
    • 使用CSS_SELECTOR

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "h2 a.clickable[onmousedown^='open_item_detail']"))).click()
      
    • 使用XPATH

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h2//a[@class='clickable' and starts-with(@onmousedown, 'open_item_detail')][contains(., 'Sample Item')]"))).click()
      
    • 注意:您必须添加以下导入:

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

    【讨论】:

    • 如何循环访问这些链接以点击并返回。当我尝试循环点击它时,只点击第一个链接。
    • @ACE 你能就你的新要求提出一个新问题吗?很乐意为您提供帮助。
    • 这个新问题已经在 SO 上被问过好几次了。搜索应该可以帮助您找到它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2021-09-04
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多