python - 使用BeautifulSoup按id解析

标签 python html beautifulsoup html-parsing

在BeautifulSoup,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>
"""

我们经常使用 提取所有链接,例如

for link in soup.find_all('a'):
    print(link.get('href'))

输出

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 文档?执行此操作的首选方法是什么?

首先,你可以获取“sister”类中的所有标签,即

soup.find_all(class_="sister")

然后呢?

最佳答案

如果您要使用 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 选择器来实现它:

soup.select("a[id^=link]")  # id starts with 'link'

关于python - 使用BeautifulSoup按id解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33508202/

相关文章:

python - 是否可以在Python(Scikit-Learn)中的KMeans中对非 float 据进行聚类?

python - 如果我使用 pip 安装模块,如何确保其他人可以在不安装该模块的情况下运行我的程序?

python - 如何在 BeautifulSoup.BeautifulStoneSoup 中维护区分大小写的标签?

python - 使用 Python 将字典分类的最佳方法

python - WLST执行存储变量 "connect()"语句

php - 有什么地方可以让我添加刷新 header 而不会导致循环吗?

c# - 如何使用带有格式的打开 xml 将 docx 转换为 html 文件

html - Css 左过渡不适用于高度和左

python - 如何避免属性错误: 'NoneType' object has no attribute 'text' webscraping subreddits?

python - 使用Python评估html表中的图像