在 Python 中抓取 HTML Table

Scrape HTML Table in Python

我正在尝试抓取美国证券交易委员会的报告页面,以提取一些关于一些股票代码的基本信息。

这里是苹果的例子 URL - https://sec.report/CIK/0000320193

页面内有一个 'Company Details' table,其中包含基本信息。我基本上只是想抓取 IRS 号码、公司所在州和地址。

只要抓取这张图表并将其保存到 PD Df 中,我就觉得很酷。我对网络抓取非常陌生,所以正在寻找一些技巧来完成这项工作!下面是我的代码,但是一旦我提取面板主体,我就不知道去哪里了。谢谢大家!

session = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
page = requests.get('https://sec.report/CIK/0000051143.html', headers = headers)
page.content

from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')

soup.find_all(class_='panel-body')

尝试使用 lxml 包而不是 BeautifoulSoup,对我来说,使用 xpath 语句查找元素更容易:

import requests
from lxml import html

session = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
page = requests.get('https://sec.report/CIK/0000051143', headers=headers)

raw_html = html.fromstring(page.text)

irs = raw_html.xpath('//tr[./td[contains(text(),"IRS Number")]]/td[2]/text()')[0]

state_incorp = raw_html.xpath('//tr[./td[contains(text(),"State of Incorporation")]]/td[2]/text()')

address = raw_html.xpath('//tr[./td[contains(text(),"Business Address")]]/td[2]/text()')[0]