beautifulsoup之CSS選擇器


BeautifulSoup支持大部分的CSS選擇器,其語法為:向tag或soup對象的.select()方法中傳入字符串參數,選擇的結果以列表形式返回。

  tag.select("string")

  BeautifulSoup.select("string")

 

源代碼示例:

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 class="mysis" href="http://example.com/elsie" id="link1">
<b>the first b tag<b>
Elsie
</a>,
<a class="mysis" href="http://example.com/lacie" id="link2" myname="kong">
Lacie
</a>and
<a class="mysis" href="http://example.com/tillie" id="link3">
Tillie
</a>;and they lived at the bottom of a well.
</p>
<p class="story">
myStory
<a>the end a tag</a>
</p>
<a>the p tag sibling</a>
</body>
</html>
"""
soup = BeautifulSoup(html,'lxml')

  1、通過標簽選擇

# 選擇所有title標簽
soup.select("title")
# 選擇所有p標簽中的第三個標簽
soup.select("p:nth-of-type(3)") 相當於soup.select(p)[2]
# 選擇body標簽下的所有a標簽
soup.select("body a")
# 選擇body標簽下的直接a子標簽
soup.select("body > a")
# 選擇id=link1后的所有兄弟節點標簽
soup.select("#link1 ~ .mysis")
# 選擇id=link1后的下一個兄弟節點標簽
soup.select("#link1 + .mysis")

  2、通過類名查找

# 選擇a標簽,其類屬性為mysis的標簽
soup.select("a.mysis")

  3、通過id查找

# 選擇a標簽,其id屬性為link1的標簽
soup.select("a#link1")

  4、通過【屬性】查找,當然也適用於class

# 選擇a標簽,其屬性中存在myname的所有標簽
soup.select("a[myname]")
# 選擇a標簽,其屬性href=http://example.com/lacie的所有標簽
soup.select("a[href='http://example.com/lacie']")
# 選擇a標簽,其href屬性以http開頭
soup.select('a[href^="http"]')
# 選擇a標簽,其href屬性以lacie結尾
soup.select('a[href$="lacie"]')
# 選擇a標簽,其href屬性包含.com
soup.select('a[href*=".com"]')
# 從html中排除某標簽,此時soup中不再有script標簽
[s.extract() for s in soup('script')] 
# 如果想排除多個呢
[s.extract() for s in soup(['script','fram']

  

  5、獲取文本及屬性

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>;
    </p>
        and they lived at the bottom of a well.
    <p class="story">...</p>
</body>
"""
from bs4 import BeautifulSoup
'''
以列表的形式返回
'''
soup = BeautifulSoup(html_doc, 'html.parser')
s = soup.select('p.story')
s[0].get_text()  # p節點及子孫節點的文本內容
s[0].get_text("|")  # 指定文本內容的分隔符
s[0].get_text("|", strip=True)  # 去除文本內容前后的空白
print(s[0].get("class"))  # p節點的class屬性值列表(除class外都是返回字符串)

 

  6、UnicodeDammit.detwingle() 方法只能解碼包含在UTF-8編碼中的Windows-1252編碼內容,

new_doc = UnicodeDammit.detwingle(doc)
print(new_doc.decode("utf8"))
# ☃☃☃“I like snowmen!”

在創建 BeautifulSoup 或 UnicodeDammit 對象前一定要先對文檔調用 UnicodeDammit.detwingle() 確保文檔的編碼方式正確.如果嘗試去解析一段包含Windows-1252編碼的UTF-8文檔,就會得到一堆亂碼,比如: ☃☃☃“I like snowmen!”.

  

  7、其它:

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>;
    </p>
        and they lived at the bottom of a well.
    <p class="story">...</p>
</body>
"""
from bs4 import BeautifulSoup
'''
以列表的形式返回
'''
soup = BeautifulSoup(html_doc, 'html.parser')
soup.select('title')  # title標簽
soup.select("p:nth-of-type(3)")  # 第三個p節點
soup.select('body a')  # body下的所有子孫a節點
soup.select('p > a')  # 所有p節點下的所有a直接節點
soup.select('p > #link1')  # 所有p節點下的id=link1的直接子節點
soup.select('#link1 ~ .sister')  # id為link1的節點后面class=sister的所有兄弟節點
soup.select('#link1 + .sister')  # id為link1的節點后面class=sister的第一個兄弟節點
soup.select('.sister')  # class=sister的所有節點
soup.select('[class="sister"]')  # class=sister的所有節點
soup.select("#link1")  # id=link1的節點
soup.select("a#link1")  # a節點,且id=link1的節點
soup.select('a[href]')  # 所有的a節點,有href屬性
soup.select('a[href="http://example.com/elsie"]')  # 指定href屬性值的所有a節點
soup.select('a[href^="http://example.com/"]')  # href屬性以指定值開頭的所有a節點
soup.select('a[href$="tillie"]')  # href屬性以指定值結尾的所有a節點
soup.select('a[href*=".com/el"]')  # 支持正則匹配

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM