【发布时间】:2021-10-30 19:02:49
【问题描述】:
尝试从以下位置提取维基百科列表:https://en.wikipedia.org/wiki/List_of_Category_5_Atlantic_hurricanes 使用 BeautifulSoup。
这是我的代码:
wiki = "https://en.wikipedia.org/wiki/List_of_Category_5_Atlantic_hurricanes"
page = urllib.request.urlopen(wiki)
soup = BeautifulSoup(page)
table=soup.find('table', class_="wikitable sortable") # The class of the list in wikipedia
Data = [[] for _ in range(9)] # I intend to turn this into a DataFrame
for row in table.findAll('tr'):
cells = row.findAll('td')
if len(cells)==9: # The start and end don't include a <td> tag
for i in range(9):
Data[i].append(cells[i].find(text=True))
除了名称列中的单个值“新英格兰”飓风之外,这非常有效。 这是包含该元素的 HTML 代码:
<td><span data-sort-value="New England !"> <a href="/wiki/1938_New_England_hurricane" title="1938 New England hurricane">"New England"</a></span></td>
那个飓风中名字的条目是'',我认为<span>和<a>之间的空格导致了这个问题。
有没有办法在.find 中解决这个问题?有没有更聪明的方法来访问维基百科中的列表?
以后如何避免这种情况?
【问题讨论】:
标签: python beautifulsoup wikipedia