【python】webスクレイピングやってみる【requests】

pythonでスクレイピングまで出来てしまうとの事で早速やってみる

あたしはphpはもう10年やっていて、phpでのスクレイピングはもう本当やりまくった

あるサイトをスクレイピングしまくってたら、そのサイトからipブロックすると怒られた事もある。。(ごめんなさい

なので、pythonでのスクレイピングも面白そうだ

まずは、pythonでスクレイピングするためのライブラリをインストールする

py -m pip install requests

これで、requestsというライブラリがインストールされた

次に、スクレイピングしたいサイトのURLを指定して、requests.get()でアクセスする

import requests
url = 'https://www.example.com'
response = requests.get(url)

これで、responseという変数にアクセスしたサイトの情報が入る

●サイトをスクレイピングしてみる

では早速サイトをスクレイピングしてみる。

スクレイピングするサイトは、世界一軽いと噂のサイト、nauru.jpにしてみる

import requests
url = 'https://nauru.jp/'
response = requests.get(url)
print(response.text)

これを実行すると、nauru.jpのHTMLが表示される

●特定のタグを抜き取る

サイトからhtmlを取得出来るなら、特定のタグを抜き取る方法もあるはず

BeautifulSoupというライブラリを使って、htmlから特定のタグを抜き取ることができる

BeautifulSoupのインストールは、以下のコマンドで行うことができる

py -m pip install beautifulsoup4

では、タイトルだけ抜き取ってみよう

import requests
from bs4 import BeautifulSoup
url = 'https://nauru.jp/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string
print(title)

これで、サイトのタイトルを抜き取ることができる

でも結果はこうなる

「ãã¦ã«å±å彿¿åºè¦³å屿¥æ¬äºåæ」

文字化けしてる!

ナウルのサイトは、文字コードがUTF-8なので、文字化けしてしまった

文字コードを指定して、requests.get()でアクセスすることで、文字化けを解消することができる

response.encoding = 'UTF-8'

で文字コードを指定出来る

import requests
from bs4 import BeautifulSoup
url = 'https://nauru.jp/'
response = requests.get(url)
response.encoding = 'UTF-8'
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string
print(title)

これを実行すると

「ナウル共和国政府観光局日本事務所」

というタイトルが表示される

●サイト内の全てのリンクを抜き取る

サイトの中にあるすべてのリンクを抜き取る場合は、以下のようなコードを書くことができる

import requests
from bs4 import BeautifulSoup
url = 'https://nauru.jp/'
response = requests.get(url)
response.encoding = 'UTF-8'
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
for link in links:
print(link.get('href'))

実行すると

「https://nauru.base.shop/
https://nauru.or.jp/
https://x.com/nanako_nsmr

と表示される

サイト内のAタグ内のURLを抜き取ることができた

●サイト内の全ての見出しを抜き取る

サイトの中にあるすべての見出しを抜き取る場合は、以下のようなコードを書くことができる

import requests
from bs4 import BeautifulSoup
url = 'https://nauru.jp/'
response = requests.get(url)
response.encoding = 'UTF-8'
soup = BeautifulSoup(response.text, 'html.parser')
headings = soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
for heading in headings:
print(heading.text)

以上、pythonでスクレイピングする方法を紹介しました
requestsとBeautifulSoupを使えば、簡単にスクレイピングすることが出来る!!

コメント