最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Selenium + XPath: element not found - Stack Overflow

programmeradmin1浏览0评论

I have a Selenium + Python + Chromedriver script which should log in to a website and click on a download button which will download a CSV file.

Inspect details of download button is:

<button id="csv-button" class="block tiny-margin-top" data-args="csv">
      CSV
</button>

and XPath is:

//*[@id="csv-button"]

but it says XPath element not found when I run the script. Please find the code below:

click_button = driver.find_element_by_xpath('//*[@id="csv-button"]')
click_button.click()

I have a Selenium + Python + Chromedriver script which should log in to a website and click on a download button which will download a CSV file.

Inspect details of download button is:

<button id="csv-button" class="block tiny-margin-top" data-args="csv">
      CSV
</button>

and XPath is:

//*[@id="csv-button"]

but it says XPath element not found when I run the script. Please find the code below:

click_button = driver.find_element_by_xpath('//*[@id="csv-button"]')
click_button.click()
Share Improve this question edited Mar 21, 2018 at 9:49 Ratmir Asanov 6,4695 gold badges29 silver badges43 bronze badges asked Mar 21, 2018 at 9:41 gosatrianigosatriani 3074 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Incase of a unique xpath identifying the WebElement if you are seeing element not found exception you need to induce WebDriverWait in conjunction with expected_conditions clause set to element_to_be_clickable as follows :

from selenium.webdriver.mon.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# other code    
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='csv-button']"))).click()

To be more granular you can use :

from selenium.webdriver.mon.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# other code    
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='block tiny-margin-top' and @id='csv-button']"))).click()

The problem seems that your xpath is not quite correct. You are using single quotes where double are required and visa versa.

Try:

click_button = driver.find_element_by_xpath("//*[@id='csv-button']")
click_button.click()

You can even try:

//button[@id='csv-button']

This will make the xpath search faster as it will look only for the button tags.

single quotes should e in the double quotes. Please see below

click_button = driver.find_element_by_xpath("//*[@id='csv-button']")

click_button.click()

see the change here:

('//*[@id="csv-button"]')   ---> ("//*[@id='csv-button']")
发布评论

评论列表(0)

  1. 暂无评论