我尝试在Python中使用Selenium从URL下载文件。我尝试使用 Options 更改默认下载目录
脚本运行时没有任何错误消息,但下载目录没有更新。我在Windows上使用的是jupyter notebook。这是我的代码:
options = Options()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option("prefs", {
"download.default_directory": r"C:\Users\danish.zahid\Downloads\pubsmed\\",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
})
# specify the title of the study you want to download
study_title = "Pan-cancer single-cell landscape of tumor-infiltrating T cells"
# start the browser and navigate to the PubMed website
s = Service(r"C:\Users\danish.zahid\Downloads\chromedriver_win32\chromedriver.exe")
browser = webdriver.Chrome(service=s, options=options)
browser.get("https://pubmed.ncbi.nlm.nih.gov/")
# find the search box, enter the study title, and submit the form
search_box = browser.find_element(By.ID, "id_term")
search_box.send_keys(study_title)
search_box.send_keys(Keys.RETURN)
# find the save button to and click it
save_button = browser.find_element(By.XPATH, "//*[@id='save-results-panel-trigger']")
save_button.click()
# Select Pubmed from drop down
dropdownlist = browser.find_element(By.ID, "save-action-format")
select_dropdown = Select(dropdownlist)
select_dropdown.select_by_visible_text("PubMed")
download_file = browser.find_element(By.XPATH, "//*[@id='save-action-panel-form']/div[2]/button[1]")
download_file.click()
browser.quit()
在网上看了很多可能的解决方案,但似乎不能使它工作,我在这里做错了什么。
2条答案
按热度按时间vmpqdwk31#
首先修改add_experimental_option:
也可以在
download_file.click()
之后使用time.sleep(10)
来添加等待时间cbjzeqam2#
这就是解决办法,朋友
如您所见,目标文件“pmid-34914499.txt”将下载到上述路径“C:\Users\PC\OneDrive\Documents\”,该路径位于Documents文件夹中。