无法使用硒使用xpath选择元素

我正在尝试使用selenium自动化过程,并且已经能够打开网页并单击链接,但是我偶然发现了一个表,该表中需要单击链接,但是我无法选择该链接并收到错误消息。需要帮助来选择该特定元素

现在这就是我所做的

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()

您可以在图片中看到我正在尝试访问findhtml.org链接。

我得到的错误是

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)

enter image description here

评论
  • 默默然
    默默然 回复

    您需要先切换到iframe,然后再处理表格元素。

       iframe = WebDriverWait(driver, 20).until(
       EC.presence_of_element_located((By.ID, '_mN_cksync_0')))
       driver.switch_to.frame(iframe)
    
       wait = WebDriverWait(driver, 10)
       element=wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(),'Go to Data')]")))
    

    要么

      wait = WebDriverWait(driver, 20)
      wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href.,'http://www.findhtml.org')]")))
    

    注意:请在您的解决方案中添加以下内容

    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    
  • nipsa
    nipsa 回复

    First you have to switch to the iframe

    例:

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

    现在您可以点击

    link = driver.find_elements_by_xpath('//a[contains(@href, 'http://www.findhtml.org')]')
    link.click()