bs4的find_all的使用方法(重点)
from bs4 import BeautifulSoup
import re
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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"><!-- E
lsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie<
/a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilli
e</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html, "lxml")
print soup.find("p")
print soup.find_all("p")
print soup.find_all("p")[2]
for tag in soup.find_all(re.compile("^b")):
print tag.name
"""
<body>...</body>
<b>...</b>
"""
print soup.find_all(["title","b"])
"""
[<title>The Dormouse's story</title>, <b>The Dormouse's story</b>]
"""
print soup.find_all(id="link2")
"""
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie<\n/a> and\n</a>]
"""
print(soup.find_all(class_="sister"))
"""
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- E\nlsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie<\n/a> and\n</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tilli\ne</a>]
"""
print(soup.find_all(text="The"))
print(soup.find_all(text="The Dormouse's story"))
"""
精确的等于才能完成匹配
[]
[u"The Dormouse's story", u"The Dormouse's story"]
"""
print(soup.find_all("a",class_="sister"))
复制代码
bs4的select的使用方法(重点)
from bs4 import BeautifulSoup
import re
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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"><!-- E
lsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie<
/a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilli
e</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html, "lxml")
print soup.select("title")
print soup.select("a")
print soup.select(".sister")
print soup.select("#link1")
print soup.select("p #link1")
"""
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- E\nlsie --></a>]
"""
print soup.select("head > title")
print soup.select("a[class="sister"]")
"""
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- E\nlsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie<\n/a> and\n</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tilli\ne</a>]
"""
print(soup.select("title")[0].get_text())
"""
The Dormouse's story
"""
复制代码
近期评论