如何用BeautifulSoup抓取<tr>内特定<td>

2024-09-29 23:18:05 发布

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

试图从纽约的wiki页面中抓取所有高中的名字。在

我已经写了足够多的脚本,可以让我得到包含高中列表的<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)

我收到的输出:

^{pr2}$

我正在寻找的输出:

The Beacon School

Tags: infromimport脚本信息htmlwiki页面
2条回答

我还通过查找<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
        ]

不如获取页面上的第一个table,遍历除第一个标题之外的所有行,并为每一行获取第一个td元素。为我工作:

for row in soup.table.find_all('tr')[1:]:
    print(row.td.text)

相关问题 更多 >

    热门问题