简体   繁体   中英

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. How can I perform click on correct element to open the link.

I am using python, selenium, chrome web driver, BeautifulSoup. All libraries are updated.

Below is the sample html snippet where there is a title I need to click on using selenium. Please let me know if you need more html source. 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.

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 :

  • Using PARTIAL_LINK_TEXT :

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

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "h2 a.clickable[onmousedown^='open_item_detail']"))).click()
  • Using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM