5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

前回の内容

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

改善点

CSVでダウンロード

手順

  • 前回からと同じく環境はGoogle Colaboratory(ローカルに環境を整えなくても試せるから)
  • ランタイムのタイプはPython3系(そっちのが良さそうだったので)
  • from google.colab import filesでファイルを扱えるようにする
  • 作成した表をCSVのファイルにして、ダウンロードする

追加したコード

from google.colab import files

# CSVに出力
filename = "topics.csv" # ファイル名の指定
df.to_csv(filename, encoding = 'utf-8') #csvへの変換、encoding指定(おまじない)
files.download(filename) # ダウンロード

全体のコード

# coding: UTF-8
import pandas as pd
from bs4 import BeautifulSoup
import requests
from google.colab import files

# アクセスする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)

# CSVに出力
filename = "topics.csv" # ファイル名の指定
df.to_csv(filename, encoding = 'utf-8') #csvへの変換、encoding指定(おまじない)
files.download(filename) # ダウンロード

補足

from google.colab import filesこれ自体はGoogle Colaboratoryで必要な機能っぽい。ローカルで動かすよう移行する時にどうなるか。
filenameを宣言してファイル名を指定。変更や使い回しがしやすいようにしている。
encoding指定はよくわからないが必要らしい。

詰まったところ

特にエラーが出ていない状態で動かなかった。ダウンロードされない状態を繰り返し、原因がわからないためChromeを再起動したら解消した。
結局何が悪かったのかは分からずじまい。

次回への課題

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?