美丽的人群得到h

2024-03-28 11:40:09 发布

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

我有以下汤:

<a href="some_url">next</a>
<span class="class">...</span>

我想从中提取

如果我只有一个标签,我可以做,但这里有两个标签。我也可以得到文本'next',但这不是我想要的。

另外,是否有一个很好的例子描述了API。我在用the standard documentation,但我在找更有组织性的东西。


Tags: the文本apiurldocumentationsome标签standard
1条回答
网友
1楼 · 发布于 2024-03-28 11:40:09

您可以通过以下方式使用find_all来查找具有href属性的每个a元素,并打印每个元素:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

结果将是:

Found the URL: some_url
Found the URL: another_url

请注意,如果您使用的是旧版本的BeautifulSoup(在版本4之前),则此方法的名称为findAll。在版本4中,美化组的方法名were changed to be PEP 8 compliant,因此应该改用find_all


如果希望所有带有href标记,可以省略name参数:

href_tags = soup.find_all(href=True)

相关问题 更多 >