我的目标是在无头模式下下载web文件。我的程序在非无头模式下下载完美,但是一旦我添加了不显示MS Edge打开的约束,下载就被忽略了。
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
driver = webdriver.Edge()
driver.get("URL")
id_box = driver.find_element(By.ID,"...")
pw_box = driver.find_element(By.ID,"...")
id_box.send_keys("...")
pw_box.send_keys("...")
log_in = driver.find_element(By.ID,"...")
log_in.click()
time.sleep(0.1) # If not included, get error: "Unable to locate element"
drop_period = Select(driver.find_element(By.ID,"..."))
drop_period.select_by_index(1)
drop_consul = Select(driver.find_element(By.ID,"..."))
drop_consul.select_by_visible_text("...")
drop_client = Select(driver.find_element(By.ID,"..."))
drop_client.select_by_index(1)
# Following files do not download with headless inculded:
driver.find_element(By.XPATH, "...").click()
driver.find_element(By.XPATH, "...").click()
在这种情况下,您可以尝试使用直接链接(到文件)和python请求下载文件。
您需要通过解析元素的href:
来获取url。从url下载并保存文件应该如下所示:
import requests as req
remote_url = 'http://www.example.com/file.txt'
local_file_name = 'my_file.txt'
data = req.get(remote_url)
# Save file data to local copy
with open(local_file_name, 'wb')as file:
file.write(data.content)
资源Chrome有不同的无头模式。如果你想下载文件,使用一个特殊的。
对于Chrome 109及以上版本,使用:
options.add_argument("--headless=new")
对于Chrome 108及以下版本,使用:
options.add_argument("--headless=chrome")
参考:https://github.com/chromium/chromium/commit/e9c516118e2e1923757ecb13e6d9fff36775d1f4
在MicrosoftEdge上以无头模式下载文件适合我版本110.0.1587.41
使用以下选项:
MicrosoftEdge: [{
"browserName": "MicrosoftEdge",
"ms:edgeOptions": {
args: ['--headless=new'],
prefs: {
"download.prompt_for_download": false,
"plugins.always_open_pdf_externally": true,
'download.default_directory': "dlFolder"
}
},
}]
没有工作,直到我添加了选项'--headless=new'
N。B:在Mac环境下使用webdriverIO
测试options.add_argument("headless=new")语法也适用于Edge。
我以前使用以下语法在无头模式下打开Edge:
from selenium import webdriver
from selenium.webdriver.edge.options import Options
options = Options()
options.add_experimental_option("prefs", {"download.default_directory": my_download_folder, "download.prompt_for_download": False, 'profile.default_content_settings.popups': False})
options.add_experimental_option("excludeSwitches", ["enable-logging"])
options.add_argument('log-level=3')
options.headless = True
browser = webdriver.Edge(options=options)
browser.get(url)
上面的代码仍然可以正常工作(以无头模式打开浏览器,点击链接等),但不允许下载文件。(你可以点击下载链接,但什么也没发生)。新语法修复了这个问题:
from selenium import webdriver
from selenium.webdriver.edge.options import Options
options = Options()
options.add_experimental_option("prefs", {"download.default_directory": my_download_folder, "download.prompt_for_download": False, 'profile.default_content_settings.popups': False})
options.add_experimental_option("excludeSwitches", ["enable-logging"])
options.add_argument('log-level=3')
options.add_argument("headless=new")
browser = webdriver.Edge(options=options)
browser.get(url)