Pythonのスクレイピング結果をGoogleSpredSheetに入力する
Pythonを使ったスクレイピング結果をGoogleSpreadSheetに入力したいな〜。と思いいろいろと調べていたら良い記事が出てきた。
まずは初期設定についてはこちら。Google Cloud Platformを利用するらしい。
実際にスクレイピング結果を入力するコードについてはこちらの記事に書いていました。
こちらのスプレッドシートを用いてスクレイピング結果を入力していく場合の実際のコードを引用させてもらうとこんな感じ。
import re import json import requests as rq import lxml.html as lx import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('クレデンシャルの秘密キー', scope) gc = gspread.authorize(credentials) #用意したスプレッドシートキーを指定する SPREADSHEET_KEY = 'スプレッドシートキー' worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1 #B3セルの値を検索クエリとして受け取る search_query=worksheet.acell('B3').value #requestsのget関数を使用して、Googleの検索結果画面(10位まで)の情報を抜き出す r = rq.get('http://www.google.co.jp/search?hl=jp&gl=JP&num=10&q='+search_query) html = r.text.encode() #コンテンツをエンコードする root = lx.fromstring(html) #パース(lxmlでスクレイピングする準備をする) #F6セルから下方向に記事URLを抜き出す i=6 for a in root.cssselect('div#search h3.r a'): worksheet.update_cell(i,6, re.sub(r'/url\?q=|&sa.*', '',a.get('href'))) #update_cell(行,列,上書きする値) i = i+1 #F列に入力されているURLをクロールして、タイトル、要約、キーワードを抜き出す #10位のサイトまで繰り替えす for i in range(6,16): try: # 古いサイトが読み込めないので無視する search = rq.get(worksheet.acell('F'+str(i)).value) #acell('F6'.value) F6〜15セルの値をクロールする search_html = search.text.encode(search.encoding) #encode(XXXX.encoding):読み込む前に文字化けするものに対応 #文字コードがUTFー8ならUTF-8でデコードしてパース if(search.encoding=='utf-8' or search.encoding=='UTF-8'): search_root = lx.fromstring(search_html.decode('utf-8')) #文字コードがそれ以外は普通にパース else: search_root = lx.fromstring(search_html) #タイトルの設定 list_title = [] for a in search_root.cssselect('title'): list_title.append(a.text) title='' for index,item in enumerate(list_title): if index==0: title = item else: title = title + ', ' +item worksheet.update_cell(i,3, title) #ディスクリプションの設定 list_description = [] for a in search_root.cssselect('meta[name="description"]'): list_description.append(a.get('content')) description='' for index,item in enumerate(list_description): if index==0: description = item else: description = description + ', ' +item worksheet.update_cell(i,4, description) #キーワードの設定 list_keywords = [] for a in search_root.cssselect('meta[name="keywords"]'): list_keywords.append(a.get('content')) keywords='' for index,item in enumerate(list_keywords): if index==0: keywords = item else: keywords = keywords + ', ' +item worksheet.update_cell(i,5, keywords) except: #例外処理:古いサイトを読み込めなかったときにする処理 worksheet.update_cell(i,3, 'エラーのため測定不能') worksheet.update_cell(i,4, 'エラーのため測定不能') worksheet.update_cell(i,5, 'エラーのため測定不能')
もしこの記事が気に入りましたらTwitterやってますのでフォローをお願いします。@nade_nadegata