kuroの覚え書き

96の個人的覚え書き

PythonでCSVのリストに従ってGoogleで検索し、結果をスクレイピングする

詳細検索画面の初期設定で検索キーワードを入れて検索をする動作を自動化する。
https://www.google.co.jp/advanced_search?q=

たとえば上の検索は
https://www.google.co.jp/search?as_q=Python+Flask+SQLAlchemy+k-kuro&as_epq=&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=&as_occt=any&safe=active&as_filetype=&as_rights=
こういうアドレスでGoogleにアクセスすると返ってくる。
ということで?as_q=のところに検索キーワードを+で区切って並べればいいわけだ。

import csv, requests, bs4

with open('output.csv', 'r') as f:
    reader = csv.reader(f)
    f2 = open('output.txt', 'w')
    f2.write('Google csv scraping results\n') 

    for row in reader:
        row2 = '+'.join(row)
        a = 'http://www.google.co.jp/search?as_q='
        b = '&as_epq=&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=&as_occt=any&safe=active&as_filetype=&as_rights='
        c = a + row2 + b

        r = requests.get(c)
        r.raise_for_status()
        r2 = r.text.encode('utf-8')

        soup = bs4.BeautifulSoup(r2, "html.parser")
        r2 = soup.select('.g')

        f2 = open('output.txt', 'a')
        f2.write('--------------------\n')
        f2.write(row2)
        f2.write('\n')
        f2.write('--------------------\n')
        for r3 in r2:
            f2.write
            f2.write('{}'.format(r3.getText()))
            f2.write('\n')
            f2.write('+++++++++++++++++++\n')
        f2.write('\n')
        f2.close()

作成したスクリプトはこんな感じ。

それによって得られた情報は

こんな感じ。

どうだろうか。