
Webスクレイピング勉強③~BeautifulSoup~
引き続き
1.BeautifulSoupでWEBページを読み込む
requestsとbeautifulsoup4をインストール

URLを指定し、そのページ情報を取得する
import requests
from bs4 import BeautifulSoup
url = 'https://scraping-for-beginner.herokuapp.com/udemy'
res = requests.get(url)
res.text
現状は単なる文字列

BeautifulSoupでHTMLとして読み込ませる
soup = BeautifulSoup(res.text, 'html.parser')
soup
綺麗な形になった

下記関数でインデントも込みで解析してくれる
print(soup.prettify())

2.ページ内の特定の要素を取得する
ページ内の「受講生の数」を取得したい。→<p>タグかつclass="subscribers"

まずは該当のタグを取得
読み込んだHTML内の全pタグを取得
soup.find_all('p')
リスト形式で取得される

下記の指定をすることで、取得した全pタグのうち、classが指定した名前(ここではsubscribers)の要素だけを抽出できる。
subscribers = soup.find_all('p', attrs={'class':'subscribers'})
取得できた

取得した要素のtextを取得することで、値を取得できる

取得した文字列のうち、数値を抽出する
取得した文字列を分割して、int形に変換
subscribers[0].text.split(':') #:でテキストを分割
subscribers[0].text.split(':')[1] #分割した2つのうち2つ目を表示
int(subscribers[0].text.split(':')[1]) #int型に変換
同様にレビューの数も取得する

同じ要領で取得完了

CSSセレクタによる取得
find_allではなくsoupのselect関数でクラス名を指定することでも取得は可能
soup.select_one('.subscribers').text

以上。勉強になりました。