如何使用BeautifulSoup从SEC N-Q doc中提取表格

时间:2015-07-16 16:25:50

标签: python web-scraping beautifulsoup

(python 2.7,BeautifulSoup4)

我正在尝试从SEC N-Q文档中提取表格内容。在此处示例html:https://www.sec.gov/Archives/edgar/data/36405/000093247115006447/indexfunds_final.htm

该文件根本没有标记。我想搜索部分' C。期货合约'并寻找下一个<表>并提取<中的内容。 tr>。有多个&C。期货合约'也出现在一份文件中。

我已尝试过以下代码,但什么都没有。

import requests, re
from bs4 import BeautifulSoup
r = requests.get("https://www.sec.gov/Archives/edgar/data/36405/000093247115006447/indexfunds_final.htm")
futures = soup.find_all(re.compile('C. Futures Contract'))
print futures

[]

1 个答案:

答案 0 :(得分:1)

首先,如果您按文本搜索,请使用text参数(从bs 4.4.0开始,参数名为string)。

除此之外,对于每个futures部分,使用find_next()查找下一个table元素。

工作代码:

import re

import requests
from bs4 import BeautifulSoup

response = requests.get("https://www.sec.gov/Archives/edgar/data/36405/000093247115006447/indexfunds_final.htm")
soup = BeautifulSoup(response.content)

futures = soup.find_all(text=re.compile('C. Futures Contract'))
for future in futures:
    for row in future.find_next("table").find_all("tr"):
        print [cell.get_text(strip=True) for cell in row.find_all("td")]