如何使用 BeautifulSoup 在 <tr> 中获取特定的 <td>
How to grab a specific <td> within a <tr> with BeautifulSoup
试图从纽约市的高中列表 wiki 页面中获取所有高中的名称。
我已经写了足够多的脚本来获取 所有 包含在 table 的 <tr>
标签中的信息高中、学术领域和入学标准 - 但我怎样才能将范围缩小到我认为 td[0]
范围内的范围(吐回 KeyError
) - 只是学校的名称?
到目前为止我编写的代码:
from bs4 import BeautifulSoup
from urllib2 import urlopen
NYC = 'https://en.wikipedia.org/wiki/List_of_high_schools_in_New_York_City'
html = urlopen(NYC)
soup = BeautifulSoup(html.read(), 'lxml')
schooltable = soup.find('table')
for td in schooltable:
print(td)
我收到的输出:
<tr>
<td><a href="/wiki/The_Beacon_School" title="The Beacon School">The Beacon School</a></td>
<td>Humanities & interdisciplinary</td>
<td>Academic record, interview</td>
</tr>
输出我求:
The Beacon School
如何获取页面上的第一个 table
,遍历除第一个 header 行之外的所有行,并为每一行获取第一个 td
元素。适合我:
for row in soup.table.find_all('tr')[1:]:
print(row.td.text)
我还设法通过查找 <td>
中的所有锚点然后查找标题来做到这一点:
titles = next(
i.get('title') for i in [
td.find('a') for td in soup.findAll('td') if td.find('a') is not None
]
试图从纽约市的高中列表 wiki 页面中获取所有高中的名称。
我已经写了足够多的脚本来获取 所有 包含在 table 的 <tr>
标签中的信息高中、学术领域和入学标准 - 但我怎样才能将范围缩小到我认为 td[0]
范围内的范围(吐回 KeyError
) - 只是学校的名称?
到目前为止我编写的代码:
from bs4 import BeautifulSoup
from urllib2 import urlopen
NYC = 'https://en.wikipedia.org/wiki/List_of_high_schools_in_New_York_City'
html = urlopen(NYC)
soup = BeautifulSoup(html.read(), 'lxml')
schooltable = soup.find('table')
for td in schooltable:
print(td)
我收到的输出:
<tr>
<td><a href="/wiki/The_Beacon_School" title="The Beacon School">The Beacon School</a></td>
<td>Humanities & interdisciplinary</td>
<td>Academic record, interview</td>
</tr>
输出我求:
The Beacon School
如何获取页面上的第一个 table
,遍历除第一个 header 行之外的所有行,并为每一行获取第一个 td
元素。适合我:
for row in soup.table.find_all('tr')[1:]:
print(row.td.text)
我还设法通过查找 <td>
中的所有锚点然后查找标题来做到这一点:
titles = next(
i.get('title') for i in [
td.find('a') for td in soup.findAll('td') if td.find('a') is not None
]