使用 BeautifulSoup 按id解析
Using BeautifulSoup to parse by id
在 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 文档本身中,这些链接列在 class "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 文档?这样做的首选方法是什么?
首先,您可以获得 class "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'
在 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 文档本身中,这些链接列在 class "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 文档?这样做的首选方法是什么?
首先,您可以获得 class "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'