BeautifulSoupを説明しているサイトはたくさんあります。
基本
BeautifulSoupの基本的な使い方については次のようなコードを書いているケースがほとんどです。
例として、このブログのタイトルを取得してみます。
import requests
from bs4 import BeautifulSoup
url = "https://stabucky.com/wp/"
response = requests.get(url)
bs = BeautifulSoup(response.content, "html.parser")
titles = bs.select("title")
print(titles[0].get_text())
from bs4 import BeautifulSoup
url = "https://stabucky.com/wp/"
response = requests.get(url)
bs = BeautifulSoup(response.content, "html.parser")
titles = bs.select("title")
print(titles[0].get_text())
実行結果
You Look Too Cool
requestsを使ってページ内容を取得してcontentを使ってバイナリとして渡す、という処理です。
通常はこれでOKです。
テキストで処理
どのサイトもこのように説明しているので「バイナリしか使えない」と思ってしまいます。
しかし実際はテキストでも使えます。
import requests
from bs4 import BeautifulSoup
url = "https://stabucky.com/wp/"
response = requests.get(url)
bs = BeautifulSoup(response.text, "html.parser")
titles = bs.select("title")
print(titles[0].get_text())
from bs4 import BeautifulSoup
url = "https://stabucky.com/wp/"
response = requests.get(url)
bs = BeautifulSoup(response.text, "html.parser")
titles = bs.select("title")
print(titles[0].get_text())
実行結果
You Look Too Cool
requestsを使ってページ内容を取得するところは同じです。
その後、textを使ってテキストとして渡しています。
実はこれでも正しく処理されます。
文字列で処理
となるとHTMLを文字列として渡しても処理できるのではないか、となります。
実際、処理できます。
import requests
from bs4 import BeautifulSoup
html = "<html><head><title>仮のタイトル</title></head></html>"
bs = BeautifulSoup(html, "html.parser")
titles = bs.select("title")
print(titles[0].get_text())
from bs4 import BeautifulSoup
html = "<html><head><title>仮のタイトル</title></head></html>"
bs = BeautifulSoup(html, "html.parser")
titles = bs.select("title")
print(titles[0].get_text())
実行結果
仮のタイトル
素のHTMLを文字列として渡しています。
これでも全く同じようにして、処理できます。
コメント