Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

Error on Python Selenium (find_element_by_xpath)

I am trying to write a list of code to automate my daily file downloading process. I am using Python Selenium for this. However, I am having trouble to locate one of the clicks.

HTMI Code as below:

<div class="card dark-blue"> <h3 data-mh="title-research" style="height: 52px;">Rated Range Prices (LT)</h3> <h4 class="disp_date">26-Jan-2021 17:47:58</h4> <div class="divider"></div> <a href="javascript:seemore('F10002');" value="F10002" class="link">See More ?</a> </div>

Here is my code:

link = driver.find_element_by_xpath("//a[@href='javascript:seemore('F10002');']")

The error msg:

InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression //*[@href='javascript:seemore('F10002');'] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[@href='javascript:seemore('F10002');']' is not a valid XPath expression.
  (Session info: chrome=88.0.4324.104)

Can anyone please enlighten me on this? Many thanks.

question from:https://stackoverflow.com/questions/65904010/error-on-python-selenium-find-element-by-xpath

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To locate the element See More ? you can use either of the following Locator Strategies:

  • Using css_selector:

    element = driver.find_element(By.CSS_SELECTOR, "div.card.dark-blue a.link[href*='seemore']")
    
  • Using xpath:

    element = driver.find_element(By.XPATH, "//div[@class='card dark-blue']//a[@class='link' and starts-with(., 'See More')]")
    

Ideally, to locate the clickable element you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.card.dark-blue a.link[href*='seemore']")))
    
  • Using XPATH:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='card dark-blue']//a[@class='link' and starts-with(., 'See More')]")))
    
  • 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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...