[英]Python Selenium Element click
With my beginner knowledge in selenium I have tried to find the click element, to the open the link.凭借我对硒的初学者知识,我试图找到点击元素,以打开链接。 There is not href for link for these items.这些项目的链接没有 href。 How can I perform click on correct element to open the link.如何单击正确的元素以打开链接。
I am using python, selenium, chrome web driver, BeautifulSoup.我正在使用 python、selenium、chrome web 驱动程序、BeautifulSoup。 All libraries are updated.所有库都已更新。
Below is the sample html snippet where there is a title I need to click on using selenium.下面是示例 html 片段,其中有一个我需要使用 selenium 单击的标题。 Please let me know if you need more html source.如果您需要更多 html 源代码,请告诉我。 This code is from a "sign in" only website.此代码来自仅“登录”的网站。
<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>
wait for the element, then find by the right xpath.等待元素,然后通过正确的 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()
To click on the element you need to induce WebDriverWait for the element_to_be_clickable()
and you can use either of the following Locator Strategies :要单击元素,您需要为element_to_be_clickable()
引入WebDriverWait ,您可以使用以下任一定位器策略:
Using PARTIAL_LINK_TEXT
:使用PARTIAL_LINK_TEXT
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Sample Item"))).click()
Using CSS_SELECTOR
:使用CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "h2 a.clickable[onmousedown^='open_item_detail']"))).click()
Using XPATH
:使用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()
Note : You have to add the following imports :注意:您必须添加以下导入:
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.