首页 > 解决方案 > find_element_by_xpath does not work when I automating downloading a csv

问题描述

I am trying to automate download a file from a database using selenium in python. I find the xpath by right click on the button and then copy the xpath. In my python code, I used find_element_by_xpath after open the website using chromedriver. But it returned an empty list but not an element. This problem was driving me crazy. Have anyone run into this problem?

Here is the code:

import time 
from selenium import webdriver
from selenium.webdriver.chrome.option import Options
def test_sanity():
    options = Options()
    options.add_argument("--disable-infobars")
    browser = webdriver.Chrome() _= 
    browser.get("ebi.ac.uk/chembl/g/#browse/activities/filter/…) 
    download = browser.find_elements_by_xpath(""".//*[@id="GladosMainContent"]/div/div/div[1]/div[2]/div[1]/div[3]/div/a[1]""") 
    print(download) 
    time.sleep(3)

标签: selenium-webdriver

解决方案


您必须等到页面完全加载后才能与CSV按钮进行交互。这完全是同步问题。下面是同步的脚本。

需要进口:

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

脚本:

url = "https://www.ebi.ac.uk/chembl/g/#browse/activities/filter/target_chembl_id%3ACHEMBL5455"
wait = WebDriverWait(driver, 10)
# navigate to application
driver.get(url)
# wait for the CSV Link and then click
csvLink = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "[data-format='CSV']")))
csvLink.click()
# wait for the download link and click
hereLink = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,".BCK-download-messages-container .BCK-download-link-container a")))
hereLink.click()
# wait for 10 seconds for the downloading to finish
time.sleep(10) # check if there is another option available to make sure if the download is completed, otherwise use this hard coded wait.

推荐阅读