[英]Python Selenium Element click
憑借我對硒的初學者知識,我試圖找到點擊元素,以打開鏈接。 這些項目的鏈接沒有 href。 如何單擊正確的元素以打開鏈接。
我正在使用 python、selenium、chrome web 驅動程序、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()
要單擊元素,您需要為element_to_be_clickable()
引入WebDriverWait ,您可以使用以下任一定位器策略:
使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.