前回の内容
改善点
- 一旦ローカルではなくGoogleスプレッドシート上にファイルを出力してみる
- 特定のファイルを開き、取得したタイトルとURLを書き込む
手順
- Google ColaboratoryでGoogleスプレッドシートを開く
- 既に取得済みの値から、A列にタイトル、B列にURLを書き込む
追加したコード
# !pip install gspread
from google.colab import auth
from oauth2client.client import GoogleCredentials
import gspread
# 認証処理
auth.authenticate_user()
gc = gspread.authorize(GoogleCredentials.get_application_default())
# ファイルを開く
# 'マイドライブ/sheet/#ファイル#'というスプレッドシートをオープン
sh = gc.open_by_key('1###Y')
worksheet = sh.get_worksheet(0) # 書き込み用ワークシートを指定
# 抽出したa要素をセルに入れ込む
for i, tag in enumerate(tags, 1):
name = tag.string # 記事名の取得
url = tag.get("href") #リンクの取得
worksheet.update_cell(i, 1, name) # 座標指定(行,列) # CSVに記入
worksheet.update_cell(i, 2, url)
全体のコード
# coding: UTF-8
# !pip install gspread
from bs4 import BeautifulSoup
import requests
from google.colab import auth
from oauth2client.client import GoogleCredentials
import gspread
# 認証処理
auth.authenticate_user()
gc = gspread.authorize(GoogleCredentials.get_application_default())
# ファイルを開く
# 'マイドライブ/sheet/#ファイル#'というスプレッドシートをオープン
sh = gc.open_by_key('1###Y')
worksheet = sh.get_worksheet(0) # 書き込み用ワークシートを指定
# アクセスする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"})
# 抽出したa要素をセルに入れ込む
for i, tag in enumerate(tags, 1):
name = tag.string # 記事名の取得
url = tag.get("href") #リンクの取得
worksheet.update_cell(i, 1, name) # 座標指定(行,列) # CSVに記入
worksheet.update_cell(i, 2, url)
補足
-
gspread
はimportだけだと使えない。!pip install gspread
でインストールしてあげる必要あり。(一旦インストールしてしまえばランタイム接続中は再度インストールする必要なし。) - for文は
enumerate
を使用して第二引数を1からに指定。スプレッドシート上の座標を指定するのに使用。 -
sh = gc.open_by_key('###')
ファイルのリンク先IDを入れる(参考リンク) -
update_cell
以外にもセル指定の仕方がある(参考リンク)
詰まったところ
- gspreadのinstallをせずにimportしてエラーを吐いていた
- pandasで作った行を挿入しようとしたが出来なかったので
enumerate
を利用してセル単位での書き込み形式にした
次回への課題
- 法律周りの確認
CSVでダウンロード- 1時間に1回取得などの動き
- 重複する内容を取得しないようにする
- 次ページ以降の取得
- 元リンクを取得
- ローカル環境で動かす
- APIを使用してスプレッドシートにアクセス new