我正在尝试使用python中的硒自动从数据库下载文件。我通过右键单击按钮找到xpath,然后复制xpath。在我的python代码中,使用chromedriver打开网站后,我使用了find_element_by_xpath。但是它返回了一个空列表,但没有返回任何元素。这个问题使我发疯。有没有人遇到这个问题?
代码如下:
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)
答案 0 :(得分:0)
您必须等到页面完全加载后才能与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.