前提・実現したいこと
python勉強中の初心者です。
https://tanuhack.com/google-scraping/
こちちらのサイトを参考に、
・pythonによるgoogle検索結果のスクレイピング
・検索結果をgoogleスプレッドシートへ
というのを行いたく、コピペで実行してみましたが、
うまくいきません。
発生している問題・エラーメッセージ
検索結果がすべて「エラーのため測定不能」でスプレッドシートに表記されます
該当のソースコード
python
1import re 2import json 3import requests as rq 4import lxml.html as lx 5import gspread 6from oauth2client.service_account import ServiceAccountCredentials 7 8scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] 9credentials = ServiceAccountCredentials.from_json_keyfile_name('クレデンシャルの秘密キー', scope) 10gc = gspread.authorize(credentials) 11 12#用意したスプレッドシートキーを指定する 13SPREADSHEET_KEY = 'スプレッドシートキー' 14worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1 15 16#B3セルの値を検索クエリとして受け取る 17search_query=worksheet.acell('B3').value 18 19#requestsのget関数を使用して、Googleの検索結果画面(10位まで)の情報を抜き出す 20r = rq.get('http://www.google.co.jp/search?hl=jp&gl=JP&num=10&q='+search_query) 21html = r.text.encode() #コンテンツをエンコードする 22root = lx.fromstring(html) #パース(lxmlでスクレイピングする準備をする) 23 24#F6セルから下方向に記事URLを抜き出す 25i=6 26for a in root.cssselect('div#search h3.r a'): 27 worksheet.update_cell(i,6, re.sub(r'/url?q=|&sa.*', '',a.get('href'))) #update_cell(行,列,上書きする値) 28 i = i+1 29 30#F列に入力されているURLをクロールして、タイトル、要約、キーワードを抜き出す 31#10位のサイトまで繰り替えす 32for i in range(6,16): 33 34 try: # 古いサイトが読み込めないので無視する 35 search = rq.get(worksheet.acell('F'+str(i)).value) #acell('F6'.value) F6〜15セルの値をクロールする 36 search_html = search.text.encode(search.encoding) #encode(XXXX.encoding):読み込む前に文字化けするものに対応 37 38 #文字コードがUTFー8ならUTF-8でデコードしてパース 39 if(search.encoding=='utf-8' or search.encoding=='UTF-8'): 40 search_root = lx.fromstring(search_html.decode('utf-8')) 41 42 #文字コードがそれ以外は普通にパース 43 else: 44 search_root = lx.fromstring(search_html) 45 46 #タイトルの設定 47 list_title = [] 48 for a in search_root.cssselect('title'): 49 list_title.append(a.text) 50 title='' 51 for index,item in enumerate(list_title): 52 if index==0: 53 title = item 54 else: 55 title = title + ', ' +item 56 worksheet.update_cell(i,3, title) 57 58 #ディスクリプションの設定 59 list_description = [] 60 for a in search_root.cssselect('meta[name="description"]'): 61 list_description.append(a.get('content')) 62 description='' 63 for index,item in enumerate(list_description): 64 if index==0: 65 description = item 66 else: 67 description = description + ', ' +item 68 worksheet.update_cell(i,4, description) 69 70 #キーワードの設定 71 list_keywords = [] 72 for a in search_root.cssselect('meta[name="keywords"]'): 73 list_keywords.append(a.get('content')) 74 keywords='' 75 for index,item in enumerate(list_keywords): 76 if index==0: 77 keywords = item 78 else: 79 keywords = keywords + ', ' +item 80 worksheet.update_cell(i,5, keywords) 81 82 except: #例外処理:古いサイトを読み込めなかったときにする処理 83 worksheet.update_cell(i,3, 'エラーのため測定不能') 84 worksheet.update_cell(i,4, 'エラーのため測定不能') 85 worksheet.update_cell(i,5, 'エラーのため測定不能')
全くどこで躓いているかわからずです、、、、
ご教示いただければ幸いです。
あなたの回答
tips
プレビュー