我正在尝试从维基百科页面https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M废弃表
我得到了html,发现包含我想要的表的部分:
<table class="wikitable sortable">
<tbody>
<tr>
<th>Postcode</th>
<th>Borough</th>
<th>Neighbourhood</th>
</tr>
<tr>
<td>M1A</td>
<td>Not assigned</td>
<td>Not assigned</td>
</tr>
<tr>
<td>M2A</td>
<td>Not assigned</td>
<td>Not assigned</td>
</tr>
<tr>
<td>M3A</td>
<td><a href="/wiki/North_York" title="North York">North York</a></td>
<td><a href="/wiki/Parkwoods" title="Parkwoods">Parkwoods</a></td>
</tr>
<tr>
<td>M4A</td>
<td><a href="/wiki/North_York" title="North York">North York</a></td>
<td><a href="/wiki/Victoria_Village" title="Victoria Village">Victoria Village</a></td>
</tr>
<tr>
<td>M5A</td>
<td><a href="/wiki/Downtown_Toronto" title="Downtown Toronto">Downtown Toronto</a></td>
<td><a href="/wiki/Harbourfront_(Toronto)" title="Harbourfront (Toronto)">Harbourfront</a></td>
</tr>
<tr>
.
.
.
然后我尝试了以下内容:
PostalCode=[]
for row in My_table.findAll('tr')[1:]:
PostalCode_cell=row.findAll('td')[0]
PostalCode.append(PostalCode_cell.text)
print(PostalCode)
输出是我所期望的:
['M1A', 'M2A', 'M3A', 'M4A', 'M5A', 'M5A', 'M6A', 'M6A', 'M7A', 'M8A', 'M9A', 'M1B', 'M1B', 'M2B', 'M3B', 'M4B', 'M4B', 'M5B', 'M5B', 'M6B', ...
但是,当我想为自治市镇和邻居做同样的事情时,我总是得到'列表索引超出范围'以下是我用于自治市镇和邻居的代码:
Borough=[]
for row in My_table.findAll('td') :
Borough_cell=row.findAll('a')[0]
Borough.append(Borough_cell.text)
print(Borough)
Neighbourhood=[]
for row in My_table.findAll('td'):
Neighbourhood_cell=row.findAll('a')[1]
Neighbourhood.append(Neighbourhood_cell.text)
print(Neighbourhood)
我注意到在自治市镇和邻里有值“未分配”(没有'a'),我不知道这些值是否导致问题。我的预期结果是将表格转换为pandas格式以供进一步处理。
是的,原因是因为有些邮政编码有链接,有些则没有。
一个更简单的方法是只需抓住自治市镇/邻居的td
并获取内部文本:
Borough=[]
for row in My_table.findAll('tr')[1:]:
Borough_cell=row.findAll('td')[1]
Borough.append(Borough_cell.text)
print(Borough)
就像你为邮政编码所做的一样。
请注意,您现在可以将代码概括为一个for循环:
postcodes = []
boroughs = []
neighbourhoods = []
for row in My_table.findAll('tr')[1:]:
postcodecell, boroughcell, neighbourcell = row.findAll('td')
postcodes.append(postcodecell.text)
boroughs.append(boroughcell.text)
neighbourhoods.append(neighbourcell.text)
此外,如果您的项目涉及大量维基百科页面和大量的抓取/解析,那么我强烈建议您使用两个资源:
您还可以使用pandas.read_html()将表格直接转换为DataFrame
import pandas as pd
df_list=pd.read_html('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M')
print(df_list[0])
输出:
Postcode Borough Neighbourhood
0 M1A Not assigned Not assigned
1 M2A Not assigned Not assigned
2 M3A North York Parkwoods
3 M4A North York Victoria Village
4 M5A Downtown Toronto Harbourfront
5 M5A Downtown Toronto Regent Park
...
[288 rows x 3 columns]