【发布时间】:2020-05-29 08:36:46
【问题描述】:
我一直在尝试使用 Beautifulsoup 在 Wikipedia 上抓取表格,但遇到了一些问题。
页面:https://en.wikipedia.org/wiki/New_York_City 桌子: enter image description here
表格:“种族构成”
在页面源中,表格似乎从第 1470 行开始。
这是我首先尝试的代码:
website_url = requests.get('https://en.wikipedia.org/wiki/New_York_City').text
soup = BeautifulSoup(website_url,'lxml')
table = soup.find('table',{'class':'wikitable sortable collapsible'})
headers = [header.text for header in table.find_all('th')]
table_rows = table.find_all('tr')
rows = []
for row in table_rows:
td = row.find_all('td')
row = [row.text for row in td]
rows.append(row)
with open('NYC_DEMO.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(row for row in rows if row)
这是错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-e6000bdafe11> in <module>
3 table = soup.find('table',{'class':'wikitable sortable collapsible'})
4
----> 5 headers = [header.text for header in table.find_all('th')]
6
7 table_rows = table.find_all('tr')
AttributeError: 'NoneType' object has no attribute 'find_all'
我想这是我们需要从维基百科页面获取的代码:
<tbody><tr>
<th>Racial composition</th>
<th>2010<sup id="cite_ref-QuickFacts2010_226-1" class="reference"><a href="#cite_note-QuickFacts2010-226">[224]</a></sup></th>
<th>1990<sup id="cite_ref-pop_228-0" class="reference"><a href="#cite_note-pop-228">[226]</a></sup></th>
<th>1970<sup id="cite_ref-pop_228-1" class="reference"><a href="#cite_note-pop-228">[226]</a></sup></th>
<th>1940<sup id="cite_ref-pop_228-2" class="reference"><a href="#cite_note-pop-228">[226]</a></sup>
</th></tr>
<tr>
<td><a href="/wiki/White_American" class="mw-redirect" title="White American">White</a></td>
<td>44.0%</td>
<td>52.3%</td>
<td>76.6%</td>
<td>93.6%
</td></tr>
<tr>
...
我猜它找不到正确的表?该页面上有很多表格,那么我如何正确指向该表格?
提前感谢您的帮助。
【问题讨论】:
-
如果你只对表格内容感兴趣,为什么不使用 pandas
read_htmlstackoverflow.com/questions/43344580/…
标签: python dataframe beautifulsoup wikipedia