尝试选择表中的行,总是获取NavigableString

2024-04-20 13:05:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从wiki页面上获取国家和海拔高度的列表,但没有成功:

以下是来自this page的相关HTML:

<table class="wikitable sortable jquery-tablesorter">
<thead>
<tbody>
<tr>
<td>

这是我的密码

^{pr2}$

错误如下:

Traceback (most recent call last):
  File "wiki.py", line 18, in <module>
    rows = tbody.find("tr")
AttributeError: 'NoneType' object has no attribute 'find'

所以我试着直接用soup.find('tr')选择行。在

这将导致NavigableString错误。我还可以尝试用配对方式检索信息吗?在


Tags: 列表html错误wikipagetable页面国家
2条回答

下面的代码对我有用-

import requests
from bs4 import BeautifulSoup

url = "https://en.wikipedia.org/wiki/List_of_countries_by_average_elevation"

response = requests.get(url)

soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table')


countries = []
altitudes = []

for row in table.find_all('tr')[1:]:
    col = row.find_all('td')
    country= col[0].text.strip()
    elevation = float(''.join(map(unicode.strip,col[1].text.split("m")[0])).replace(',',''))
    countries.append(country)
    altitudes.append(elevation)

print countries,'\n',altitudes

如果您转到页面源代码并搜索tbody,则会得到0个结果,因此这可能是第一个问题的原因。似乎Wikipedia使用了一个自定义的<table class="wikitable sortable">,而没有指定tbody。在

第二个问题{{cd6>不需要使用第二个。所以你想

rows = soup.find_all("tr")

希望这有帮助:)

相关问题 更多 >