简体   繁体   中英

Selenium Python: Select <a href=“#” </a>

How can I select a button with the following HTML:

<a href="#" class="js-buy ncss-brand ta-sm-c u-uppercase pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg d-sm-b d-lg-ib test-buyable ncss-btn bg-black text-color-white">Kaufen 210,00&nbsp;€</a>

The following is on I want to click on the black 'Kaufen' button. I have tried the following:

buy = ui.WebDriverWait(self.driver, 30).until(EC.presence_of_element_located((By.XPATH, '//*[@id="j_c29"]/div[1]/a')))
buy.click()

I get error:

File "/Users/xxx/test.py", line 101, in <module>
    obj.run()
  File "/Users/xxx/test.py", line 66, in run
    buy = ui.WebDriverWait(self.driver, 30).until(EC.presence_of_element_located((By.XPATH, '//*[@id="j_c29"]/div[1]/a')))
  File "/Users/xxx/Library/Python/2.7/lib/python/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

Use this code:

WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='j_c29']/div[1]/a"))).click()

If you want to remove the "Deine Cookie-Einstellungen" popup use this code just before the code above:

WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div/div[3]/div/div/div/div/div/div/div/div/div/div/div/div/div[3]/div[2]/div"))).click() 

As per the HTML you have shared to click() on the element you need to induce WebDriverWait along with expected_conditions clause as element_to_be_clickable instead of presence_of_element_located and you can use either of the following options :

  • Partial Link Text :

     WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Kaufen"))).click() 
  • XPATH :

     WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='js-buy ncss-brand ta-sm-c u-uppercase pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg d-sm-b d-lg-ib test-buyable ncss-btn bg-black text-color-white' and contains(.,'Kaufen')]"))).click() 

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