简体   繁体   中英

unable to select an element using xpath using selenium

I'm trying to automate a process using selenium and have been able to open a webpage and click on links, however I stumbled upon a table in which a link needs to be clicked but I'm unable to select that link and getting an error. need help to select that particular element

right now this is what I've done

elem2=browser.find_elements_by_xpath('/html/body/div[3]/table/tbody/tr[1]/td[2]/div[2]/table/tbody/tr[7]/td[3]/a::text')
elem2.click()

you can see in the picture that I'm trying to access the findhtml.org link.

the error that I get is

InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression /html/body/div[3]/table/tbody/tr[1]/td[2]/div[2]/table/tbody/tr[7]/td[3]/a::text because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '/html/body/div[3]/table/tbody/tr[1]/td[2]/div[2]/table/tbody/tr[7]/td[3]/a::text' is not a valid XPath expression.
  (Session info: chrome=81.0.4044.113)

在此处输入图像描述

First you have to switch to the iframe

Example:

frame = browser.find_elements_by_xpath('//iframe[contains(@src, \'hbx.media.net\')]')
browser.switch_to.frame(frame)

Now you can click

link = browser.find_elements_by_xpath('//a[contains(@href, \'http://www.findhtml.org\')]')
link.click()
browser.get('https://publicrecords.netronline.com/state/IL/county/dupage')

wait = WebDriverWait(browser, 20)
wait.until(EC.element_to_be_clickable((By.XPATH, "//td[contains(text(),'DuPage Supervisor of Assessments')]//following-sibling::td[2]//a"))).click()

output:

在此处输入图像描述

Note: please add below imports to your solution

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

To click on the specific link try below code.

Induce WebDriverWait () and presence_of_element_located () and following xpath.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://publicrecords.netronline.com/state/IL/county/dupage")
element=WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,"//a[@href='http://www.dupageco.org/PropertyInfo/PropertyLookUp.aspx' and contains(.,'Go to Data')]")))
element.location_once_scrolled_into_view
element.click()

Please note the element is not inside any iframe

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