1
0

More than 3 years have passed since last update.

Pythonウェブページのデータを取得

Last updated at Posted at 2021-05-16

Pythonウェブページのデータを取得

Pythonにライブラリrequests、解析ライブラリBeautifulSoupを介して情報を取得します、ここではYahoo(https://www.yahoo.com/)を例にします、ホームページTrending Nowの内容を取得します。

1)まずはライブラリrequests、BeautifulSoupをインポート
2)requests.get(url)を使ってウェブページのすべてのコンテンツを取得
java
requests.get(url)

3)取得したウェブページのコンテンツをBeautifulSoupタイプに変換
java
bs = BeautifulSoup(result, 'html.parser')

4)解析Yahoo(https://www.yahoo.com/)のTrending Nowエリア、探し出す他の内容との違い、分析し発見するclass属性は唯一です。この属性を使って値を取得します。
find_all(class_='XXX')方法を使って値を取得します。
※classがpythonのキーワード、だからclass_を使用します。
その他ラベル、属性は直接使用できます。
例:
python
find_all('a')
find_all(id='link2')
find_all(["a", "span"])

など。
イメージ:
image1.png

ソースコード

# ライブラリ
import requests
# 解析ライブラリ
from bs4 import BeautifulSoup

# ウェブページurl
r = requests.get("https://www.yahoo.com/")
# タイプ
result = r.text
# BeautifulSoupタイプに変換
bs = BeautifulSoup(result, 'html.parser')
print("データ:")
# class属性を使って値を取得します
data1 = bs.find_all(class_='Mstart(-2px) C($c-fuji-grape-jelly):h C($c-fuji-inkwell) Fz(12px) Fw(600)')
# ループ出力
for i in data1:
    print(i.text)

実行結果

C:\>"C:\Program Files\Python37\python.exe" D:/WeChat_Robot/CatchData/catchdata.py
データ:
 Carey Mulligan
 Hideki Matsuyama
 Kid Cudi
 Prince Phillip
 Biglietti da visita
 Antivirus Kaspersky
 Forni elettrici
 Camicie uomo
 Mascherine online
 Spesa online

Process finished with exit code 0
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0