【问题标题】:Headless mode disable python web file downloading无头模式禁用 python web 文件下载
【发布时间】:2023-01-21 02:10:10
【问题描述】:

我的目标是在无头模式下下载网络文件。当不在无头模式下时,我的程序可以完美下载,但是一旦我添加了不显示 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 selenium selenium-webdriver downloading-website-files


    【解决方案1】:

    在这种情况下,您可以尝试使用直接链接(指向文件)和 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)
    

    resource

    【讨论】:

    • 我找不到文件下载的 URL,只能找到网站。文件下载只有在我选择了下拉列表后才会出现,并且页面会自动更新。
    • 您可以将 page_source 或 url 添加到网站,以及所需的按钮元素吗?
    • 但是,我在网页上下载的信息是自行决定的,我无法提供对该页面的访问权限。
    • 嗯,我认为应该有一种方法可以识别直接链接。您可以尝试使用网络(浏览器开发人员工具)选项卡来获取文件请求的 url。
    【解决方案2】:

    Chrome 有不同的无头模式。如果要下载文件,请使用其中一种特殊文件。

    对于 Chrome 109 及更高版本,请使用:

    options.add_argument("--headless=new")
    

    对于 Chrome 108 及以下版本,请使用:

    options.add_argument("--headless=chrome")
    

    参考:https://github.com/chromium/chromium/commit/e9c516118e2e1923757ecb13e6d9fff36775d1f4

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-27
      • 2018-06-11
      • 2022-09-23
      • 2020-02-10
      • 2021-09-12
      • 2020-05-29
      相关资源
      最近更新 更多