Python Selenium:如何通过execute_script下载
我用Python做了一个小应用,使用Selenium和 Firefox。我希望在点击一个锚点时,文件能够被下载,而不是在新标签页中打开(PDF文件)。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
URL="https://no.net.com/INFO/details.xhtml"
options = webdriver.FirefoxOptions()
service=webdriver.FirefoxService(executable_path='/.../geckodriver')
driver = webdriver.Firefox(options=options,service=service)
driver.get(URL)
objects = driver.find_elements(By.CSS_SELECTOR, "a > span.documents-text")
print(f"Array[{len(objects)}]") # gives 3
for o in objects:
print(o.text)
parent = o.find_element(By.XPATH, "./..") # this element is a anchor element
try:
# A strange div is hiding the element
# parent.click() # doesnt function
# so I must run the following
driver.execute_script("arguments[0].click();", parent)
except:
print("-- Click failed")
raise
每次点击都能正常执行,但有3 个PDF文件在Firefox浏览器的新标签页中被打开。
我该如何把这些文件下载下来,而不是在浏览器中打开?
解决方案
execute_script("arguments[0].click()", element) 只会触发点击。它不能控制Firefox是打开还是下载链接的文件。这个行为由Firefox的偏好设置控制。对于PDFs,通常关键的一步是禁用Firefox内置的PDF查看器,这可以通过pdfjs.disabled=True来实现。然后为application/pdf配置browser.helperApps.neverAsk.saveToDisk。
你可以试试这个:
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
URL = "https://no.net.com/INFO/details.xhtml"
download_dir = str(Path.cwd() / "downloads")
Path(download_dir).mkdir(exist_ok=True)
options = webdriver.FirefoxOptions()
options.set_preference("browser.download.folderList", 2)
options.set_preference("browser.download.dir", download_dir)
options.set_preference("browser.download.manager.showWhenStarting", False)
# Save PDFs
options.set_preference(
"browser.helperApps.neverAsk.saveToDisk",
"application/pdf,application/octet-stream"
)
#disable Firefox's built-in PDF viewer
options.set_preference("pdfjs.disabled", True)
driver = webdriver.Firefox(options=options)
driver.get(URL)
objects = driver.find_elements(By.CSS_SELECTOR, "a > span.documents-text")
for o in objects:
parent = o.find_element(By.XPATH, "./..")
driver.execute_script("arguments[0].click();", parent)
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。