简体   繁体   中英

How to click on td element using selenium python

So I'm Fairley new to selenium and I'm attempting click on a table but I can't seem to find it. Below I have posted my code along with a screen shot of what I'm trying to click on.

Here is my code:

competitorPrices = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, "Competitor Prices"))).click()

HTML snapshot:

html代码

Error:

这是我遇到的错误

Element snapshot:

这是我想点击的内容

I would try something like this:

...
import time
time.sleep(5)
xpath = "//*[contains(text(),'Competitor Prices')]"
element = driver.find_element(by=By.XPATH, value=xpath)
competitorPrices = driver.execute_script("$(arguments[0]).click();", element) 

Sometimes the method element_to_be_clickable doesn't work out of the box. In this cases to debug I use time.sleep so I can understand better the problem

The desired element is a <td> not an <a> tag. Hence LINK_TEXT won't work.

table_td

Moreover click() doesn't returns anything, so competitorPrices will be always None which you may remove.


Solution

You can use either of the following locator strategies :

  • Using CSS_SELECTOR :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "table#tblTabStrip td[ch^='CompetitorPrices']"))).click()
  • Using XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//table[@id='tblTabStrip']//td[text()='Competitor Prices']"))).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