LoginSignup
5
6

More than 5 years have passed since last update.

スクレイピングの学習 Python3系 その1

Last updated at Posted at 2018-08-17

とりあえず何か動かしたい

progateでPython入門を一通り終えたが、これだけで何か作れる感じがしない

とりあえず何か動かそう

ググった感じ簡単なスクレイピングなら出来そう

やること

ニュースサイトから記事タイトルとリンク先urlを取得

手順

  • 環境はGoogle Colaboratory(ローカルに環境を整えなくても試せるから)
  • ランタイムのタイプはPython3系(そっちのが良さそうだったので)
  • 対象とするサイトを決定(日頃見てるニュートピにした)
  • 各種モジュール等を使って取得していく

書いたコード

# coding: UTF-8
import pandas as pd
from bs4 import BeautifulSoup
import requests

# アクセスするURL = ニュートピ
url = "https://newstopics.jp/"

# htmlを取得、BeautifulSoupで扱う
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser') # BeautifulSoupの初期化

# aタグの中から、class=titleの含まれたものを取得
tags = soup.find_all("a", {"class": "title"})
# データフレームを作成。列名 name=記事名, url=url
columns = ["name", "url"]
df = pd.DataFrame(columns=columns) 

# 抽出したa要素を行列に入れ込む
for tag in tags:
    name = tag.string # 記事名の取得
    url = tag.get("href") #リンクの取得
    se = pd.Series([name, url], columns) # 行を追加
    print(se)
    df = df.append(se, columns)

補足

# coding: UTF-8←これよく分からない。必要っぽいのでつけた。

import pandas as pd
from bs4 import BeautifulSoup
import requests

必要な機能をimportしている。各モジュールの機能についてはググるとめっちゃ解説してるサイトが大量にある。

詰まったところ

  • 頻繁にinvalid character in identifierが出た。 日本語入力でスペースとか打ってるらしい。一旦消して書き直すとほぼ治る。
  • コードには残らなかったが、リストを記事ごとに作られているdivから作った。for文でその中から再度aタグを取り出すなどした。でも普通にaタグから取得した方が無駄がないと思って切り替え。そしたら↓のエラー。
  • 結構な時間'NoneType' object has no attribute 'string'でハマった。aタグしか入れていないリストの要素からaタグを取り出そうとしていたのが問題っぽい。
# エラーの出てたコード
name = tag.a.string # 記事名の取得
url = tag.a.get("href") #リンクの取得

# 解消したコード
name = tag.string # 記事名の取得
url = tag.get("href") #リンクの取得

次回への課題

  • 法律周りの確認
  • CSVでダウンロード
  • 1時間に1回取得などの動き
  • 重複する内容を取得しないようにする
  • 次ページ以降の取得
  • 元リンクを取得
  • ローカル環境で動かす
5
6
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
5
6