手动单击链接时,Python和Selenium会弹出一个对话框,而不是自动下载的对话框

如何解决手动单击链接时,Python和Selenium会弹出一个对话框,而不是自动下载的对话框

我正在使用Python访问SEC网站以下载10-K电子表格。我创建了代码,请求用户输入股票行情代码,成功打开Firefox,访问https://www.sec.gov/edgar/searchedgar/companysearch.html的Edgar搜索页面,并输入正确的股票代码。问题是自动下载电子表格并保存。

现在,我可以手动单击“查看Excel电子表格”,然后自动下载电子表格。但是,当我运行Python代码时,会从Firefox看到一个对话框。我将Firefox设置为自动下载,我尝试使用'find_element_by_xpath','find_element_by_css_selector',但两者都无法简单地下载文件。这两种方法仅调用同一个对话框。我尝试了“ find_element_by_link_text”,但收到有关无法找到“查看Excel电子表格”的错误消息。我的示例股票代号是Caterpillar的CAT(纽约证券交易所:CAT)。我的代码如下:

import selenium.webdriver.support.ui as ui
from pathlib import Path
import selenium.webdriver as webdriver
import time

ticker = input("please provide a ticker symbol: ")

# can do this other ways,but will create a function to do this 
def get_edgar_results(ticker):
        url = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=" + str(ticker) + "&type=10-k&dateb=20200501&count=20"

# define variable that opens Firefox via my executable path for geckodriver
    driver = webdriver.Firefox(executable_path=r"C:\Program Files\JetBrains\geckodriver.exe")

 # timers to wait for the webpage to open and display the page itself
    wait = ui.WebDriverWait(driver,40)
    driver.set_page_load_timeout(40)
    driver.get(url)

    # timers to have page wait for the page to load.
    # seemed that the total amount of time was necessary; not sure about these additional lines
    driver.set_page_load_timeout(50)
    wait = ui.WebDriverWait(driver,50)
    time.sleep(30)

    # actual code to search the resulting page for the button to click and access the excel document for download
    annual_links = driver.find_element_by_xpath('//*[@id="interactiveDataBtn"]')
    annual_links.click()

    # need to download the excel spreadsheet itself in the "financial report"
    driver.set_page_load_timeout(50)
    wait = ui.WebDriverWait(driver,50)

    excel_sheet = driver.find_element_by_xpath('/html/body/div[5]/table/tbody/tr[1]/td/a[2]')
    excel_sheet.click()
    # i'm setting the resulting dialog box to open and download automatically from now on. if i want to change it back
    # i'll need to use this page:  https://support.mozilla.org/en-US/kb/change-firefox-behavior-when-open-file
    # Testing showed that dialog box "open as" probably suits my needs better than 'save'.

    driver.close()
    driver.quit()


get_edgar_results(ticker)


任何帮助或建议,我们将不胜感激。谢谢!

解决方法

这并不是基于您的实际代码或Selenium的工作方式的建议,而是在尝试从网络上收集信息时的更一般性建议。

如果有机会,通过其API访问网站比通过Selenium尝试相同的任务对编程更友好。当您使用Selenium进行网络爬网时,通常情况下,网站的行为与通过普通浏览器访问时的行为不同。这可能有多种原因,其中最重要的原因可能是网站有意阻止了Selenium之类的自动浏览器访问它们。

在这种情况下,EDGAR SEC provides an HTTPS access service可以使您获得所需的信息。

无需深入研究这些数据,使用诸如requests之类的http请求库来请求此信息并以这种方式进行保存应该不是很困难。

import requests

result = requests.get("https://www.sec.gov/Archives/edgar/data/18230/000001823020000214/Financial_Report.xlsx")

with open("file.xlsx","wb") as excelFile:
    excelFile.write(result.content)

唯一的困难在于获得股票行情指示器的CIK来构建上述URL,但是使用相同的API信息应该不会太困难。

EDGAR网站通过其URL相当透明地向您公开其数据。您可以绕过所有Selenium怪异之处,而只需构建URL,然后直接请求信息,而无需加载所有JavaScript等。

编辑:您也可以以更具编程性的方式浏览此信息。上面的链接提到edgar / full-index中的每个目录还提供了一个JSON文件,该文件易于计算机读取。因此,您可以请求https://www.sec.gov/Archives/edgar/full-index/index.json,解析出您想要的年份,请求该年,解析出您想要的季度,请求该季度,然后解析出您想要的公司,并要求该公司的信息,等等。>

例如,要获取Caterpillar的CIK编号,您将从company.gz中获取并解析您的https://www.sec.gov/Archives/edgar/full-index/2020/QTR4.json文件,将其解析为数据帧,然后在其上找到带有CATERPILLAR INC的行,从关联的.txt文件中找到CIK和登录号,然后找到正确的URL以下载其Excel文件。有点circuit回,但是如果您可以找到一种方法来跳至CIK号码,则可以减少所需的请求数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res