requestsの使い方と文字化け対策

PythonでスクレイピングするにはBeautifulSoupなどを使いますが、さほど複雑でなければHTMLを取得して処理したほうが早いです。
この場合、requestsを使うと簡単です。

まずrequestsをインストールします。

$ pip install requests

次のように書きます。

import requests
response = requests.get(url)
html = response.text

元のHTMLがUTF-8ならば問題ないですが違う場合は次のようにします。

import requests
response = requests.get(url)
response.encoding = response.apparent_encoding
html = response.text

エンコーディングを指定します。

コメント

タイトルとURLをコピーしました