使用beauthoulsoup按id解析

2024-10-08 18:25:34 发布

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

在BeautifulGroup中,bs4版本文档http://www.crummy.com/software/BeautifulSoup/bs4/doc/

将列出一个HTML文档:

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

我们通常使用

^{pr2}$

输出

http://example.com/elsie
http://example.com/lacie
http://example.com/tillie

在HTML文档中,这些链接列在“sister”类下,并带有id标记

<a class="sister" href="http://example.com/elsie" id="link1">
<a class="sister" href="http://example.com/lacie" id="link2">
<a class="sister" href="http://example.com/tillie" id="link3">

在实际的网站中,我注意到这些id标记通常是一个数字列表,例如id="1"。有没有办法单独使用id标记来解析HTML文档?最好的方法是什么?在

首先,你可以得到“姐妹”类中的所有标签

soup.find_all(class_="sister")

然后呢?在


Tags: and文档comidhttptitleexamplehtml
1条回答
网友
1楼 · 发布于 2024-10-08 18:25:34

如果要用find_all()来解决它,可以使用正则表达式或函数:

soup.find_all("a", id=re.compile(r"^link\d+$")  # id starts with 'link' followed by one or more digits at the end of the value
soup.find_all("a", id=lambda value: value and value.startswith("link"))  # id starts with 'link'

或者,您可以使用CSS选择器

^{pr2}$

相关问题 更多 >

    热门问题