Python 硒元素点击

Python Selenium Element click

凭借我在 selenium 方面的初学者知识,我试图找到点击元素,以打开 link。这些项目没有 link 的 href。如何执行单击正确的元素以打开 link.

我正在使用 python、硒、chrome 网络 driver、BeautifulSoup。所有库都已更新。

下面是示例 html 片段,其中有一个标题,我需要使用 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>

等待元素,然后通过正确的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()

点击需要诱导的元素WebDriverWait for the element_to_be_clickable() and you can use either of the following :

  • 使用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