【问题标题】:Web scraping links within table with BeautifulSoup returns NoneType and empty table using Python使用 BeautifulSoup 抓取表中的 Web 链接返回 NoneType 和使用 Python 的空表
【发布时间】:2022-01-13 02:00:17
【问题描述】:

我试图通过网络抓取所有表格 N-MFP2,然后打开链接以抓取表格中的信息。但是,我被困在检索表格上。我尝试了多种网页抓取方法,包括beautifulSoup和selenium,但返回的是空的,我无法进一步获取行数据。感谢任何帮助,因为我已经解决了这个问题超过 3 个小时。

我的代码如下:

# Create an URL object
url = 'https://www.sec.gov/edgar/browse/?CIK=843781'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser') # it does not work even with "lxml"
# Obtain information from tag <table>
table = soup.find("table", id="filingsTable")

网页:https://www.sec.gov/edgar/browse/?CIK=843781

The table screenshot is here; Form N-MFP2 is highlighted as red

【问题讨论】:

  • BeautifulSoup 不执行 JavaScript。

标签: python beautifulsoup


【解决方案1】:

该表是动态呈现的。您可以从 json 文件访问数据源。一旦你有了它,它只是拉出 accessionNumber 然后创建适当的 url 来访问链接。

import requests
import pandas as pd

# Create an URL object
cik = 843781
cik_padded = f'{cik:010}'
url = f'https://data.sec.gov/submissions/CIK{cik_padded}.json'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
jsonData = requests.get(url, headers=headers).json()

df = pd.DataFrame(jsonData['filings']['recent'])

nmfp2 = df[df['form'] == 'N-MFP2']

不确定您想要从链接页面获得什么,但是一旦您获得相关数据以创建 url,您就可以开始获取链接数据页面。注意:文档的链接也在那里......所以如果这是你所追求的,你可以使用它来代替。但就像我说的,不知道你想从这里得到什么。

for idx, row in nmfp2.iterrows():
    accessionNumber = row['accessionNumber']
    accessionNumber_alt = ''.join(accessionNumber.split('-'))
    url = f'https://www.sec.gov/Archives/edgar/data/{cik_padded}/{accessionNumber_alt}/{accessionNumber}-index.htm'

    response = requests.get(url, headers=headers)    
    dfs = pd.read_html(response.text)
    
    print('\n')
    for table in dfs:
        print(table)

【讨论】:

  • 非常感谢!这很有帮助。你能解释一下代码“jsonData['filings']['recent']”吗?第一个 ["fillings"] 和第二个参数 ["recent"] 表示什么,你从哪里得到 ["recent"]?我对 JSON 不是很熟悉。
  • JSON(你会在 python 中看到的字典和列表)基本上是键:值对的结构(值也可以是键:值对......所以嵌套的 json 结构)。您可以通过调用这些键来获取这些值。请参阅我在上面添加的图像示例)。 recent 只是我们所追求的数据的关键
猜你喜欢
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2018-12-09
  • 2022-12-17
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 2021-11-15
相关资源
最近更新 更多