【发布时间】:2017-09-27 14:05:58
【问题描述】:
我正在尝试从网站http://www.house.gov/representatives/ 上的表格中获取一些信息 具体来说,我想从“按姓氏排列的代表目录”表中获取有关代表的信息。到目前为止,我可以从网站下载 HTML 并将其写入文件,但是当使用 bs4 解析和抓取我想要的特定表格时,它只抓取每个表格的第一行。
这是因为HTML表格的每一行都有一个额外的标签:
<tr>
<td><a href="https://abraham.house.gov/">
Abraham, Ralph </a>
</td>
<td>Louisiana 5th District</td>
<td>R</td>
<td>417 CHOB</td>
<td>202-225-8490</td>
<td>Agriculture<BR>Armed Services<BR>Science, Space, and Technology</td>
</td>
</tr>
最后一个 /td 标记以某种方式导致 bs4 无法抓取其余行。我确实进行了手动测试并删除了一些额外的标签,然后我取回了所有行,所以我知道额外的标签是问题所在。到目前为止,这是我的 python 代码:
import bs4, requests
res = requests.get('http://www.house.gov/representatives/')
res.raise_for_status()
file = open('HouseReps.html', 'wb')
for chunk in res.iter_content(100000):
file.write(chunk)
file = open('HouseReps.html')
soup = bs4.BeautifulSoup(file, 'html.parser')
table = soup.select('table[title="Representative Directory By Last Name"]')
print(table)
我也尝试过使用 prettify() 但这也无济于事。关于如何清理 HTML 以便我可以使用 bs4(或其他东西)来解析和提取我需要的表的任何想法?
谢谢!
【问题讨论】: