LoginSignup
4
2

More than 1 year has passed since last update.

【え、簡単すぎ...!?】pythonで簡単にスクレイピング をしてみたメモ

Posted at

環境構築

いつも通りこれで環境構築完了する。

requests

htmlを取得する目的

pip install requests

でrequests使えるようにする

import requests
url="https://qiita.com/1000ch/items/93841f76ea52551b6a97"
r = requests.get(url)

こんな感じでrequest.getの引数に取得するurlをいれる

BeautifulSoup

requestsで取得したhtmlを加工して扱えるようにする目的

一つ目の要素を取得する

import requests 
from bs4 import BeautifulSoup #追加
url="https://qiita.com/1000ch/items/93841f76ea52551b6a97"
r = requests.get(url)
#print(r.text)
soup = BeautifulSoup(r.text, "html.parser") #追加 
result = soup.find("h2").text #追加
print(result)

6行目の"html.parser"を抜くと

scraping.py:6: GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

て言われます。簡単に言うと
「htmlパーサを選択してないから私が一番合ってそうな"html.parser"にしておいたよ。私だからいいけど他の環境だったら違うの選んでおかしいことになるかもだょ.....」
なので念のため"html.parser"はいれておく

r.text→html取得
soup.h2.text→h2だけだとタグとかも含まれるのでtextにする。allないから最初だけ

任意の要素の取得

find_all('h2').text→✖︎
見てみるとリストなので

result = soup.find_all("h2")[0]

このように.textだった部分にインデックス番号を表記することで任意の要素が取得できる

これではタグも含まれているため.textを書きたいがエラーになるから

for i, h2_tag in enumerate(soup.find_all('h2')): 
    print(i,h2_tag.text)

これで任意の要素のテキストのみを出力できる

クラスを指定して要素を取得する

class_でクラスを指定することでそのクラス(fragment)の要素のみ取得できる

result = soup.find_all("span", class_="fragment")
print(result)

記事本文からのみ取得する

body = soup.find["必要な範囲のタグ"] 
body.find_all(["h2","h3"])

のようにfindを二回使うことで限られた範囲内から検索することができる

困ったエラー

AttributeError: 'NoneType' object has no attribute 'find_all'

4
2
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
4
2