selenium-webdriver - 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)
解决方案
您必须等到页面完全加载后才能与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.
推荐阅读
- discord.py - discord.ext.commands.errors.CommandInvokeError 命令引发异常:NameError: name 'self' is not defined
- flutter - Flutter - 忽略拇指向下
- react-native-mapbox-gl - MapboxGL.SymbolLayer 过滤表达式以检查数组中的 id
- javascript - Django LeafletWidget 自定义几何样式
- python - 基于输入数据的 TensorFlow 持续训练
- python - 如何在 Django ORM 中使用 prefetch_related 表计数进行过滤?
- java - 我需要什么集合来存储对象及其数量?
- html - 尝试使用 CSS flex 制作方形图像墙,但第一行的行为不如预期
- c++ - SDL 音频回调不产生声音
- python - 使用 Python 在 TCP 端口上进行 T24 Telnet 连接