bs 4の使い方
21086 ワード
ここに目次の見出しを書きます
BS4
インストール
使用方法
メリット
Python標準ライブラリ
BeautifulSoup(markup, “html.parser”)
Pythonの内蔵標準ライブラリは、ドキュメントのフォールトトレランスに適した速度で実行できます.
lxml HTML解析器
BeautifulSoup(markup, “lxml”)
高速ドキュメントのフォールトトレランス機能
lxml XML解析器
BeautifulSoup(markup, [“lxml-xml”]) BeautifulSoup(markup, “xml”)
速度が速くXMLを唯一サポートする解析器
html5lib
BeautifulSoup(markup, “html5lib”)
最適なフォールトトレランスは、ドキュメントをブラウザで解析してHTML 5形式のドキュメントを生成します.
対象の種類
soup = BeautifulSoup('Extremely bold')
tag = soup.b
type(tag)
#
tag.name
# 'b'
tag.attrs
# {u'class': u'boldest'}
tag.string
#Extremely bold
html_doc = """
<html><head><title>The Dormouse's storytitle>head>
<body>
<p class="title"><b>The Dormouse's storyb>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">Elsiea>,
<a href="http://example.com/lacie" class="sister" id="link2">Laciea> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilliea>;
and they lived at the bottom of a well.p>
<p class="story">...p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
の検索soup.find_all('b')
# [The Dormouse's story]
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
# body
# b
soup.find_all(["a", "b"])
# [The Dormouse's story,
# Elsie,
# Lacie,
# Tillie]
soup.find_all(id='link2')
# [Lacie]
soup.find_all(href=re.compile("elsie"))
# [Elsie]
soup.find_all("a", class_="sister")
# [Elsie,
# Lacie,
# Tillie]
soup.select("title")
# [The Dormouse's story ]
soup.select("p nth-of-type(3)")
# [...
]
soup.select("body a")
# [Elsie,
# Lacie,
# Tillie]
soup.select("html head title")
# [The Dormouse's story ]
soup.select("head > title")
# [The Dormouse's story ]
soup.select("p > a")
# [Elsie,
# Lacie,
# Tillie]
soup.select("p > a:nth-of-type(2)")
# [Lacie]
soup.select("p > #link1")
# [Elsie]
soup.select("body > a")
# []
soup.select("#link1 ~ .sister")
# [Lacie,
# Tillie]
soup.select("#link1 + .sister")
# [Lacie]
soup.select(".sister")
# [Elsie,
# Lacie,
# Tillie]
soup.select("[class~=sister]")
# [Elsie,
# Lacie,
# Tillie]
soup.select("#link1")
# [Elsie]
soup.select("a#link2")
# [Lacie]
soup.select("#link1,#link2")
# [Elsie,
# Lacie]
soup.select('a[href]')
# [Elsie,
# Lacie,
# Tillie]
soup.select('a[href="http://example.com/elsie"]')
# [Elsie]
soup.select('a[href^="http://example.com/"]')
# [Elsie,
# Lacie,
# Tillie]
soup.select('a[href$="tillie"]')
# [Tillie]
soup.select('a[href*=".com/el"]')
# [Elsie]
soup.select_one(".sister")
# Elsie