LoginSignup
7
3

More than 5 years have passed since last update.

与えたキーワードを掛け合わせて自動でGoogle検索

Last updated at Posted at 2018-07-07

企画とか考えるのすごい苦手なんですよ。。

入力したキーワードを掛け合わせてGoogle検索、結果件数を一覧表示してみようと思います。
検索結果の件数から、すでに世の中で流行っているのか、はたまたこれから流行るビジネスアイディアに繋がるかも??みたいに、企画のヒントとかになればなぁという思いです。

※めちゃくちゃ安易ですが、python, スクレイピング勉強中の身なので。。

まずはソースコード全体です。

#!/usr/bin/env python
# coding: UTF-8
import requests as web
from bs4 import BeautifulSoup

# キーワードを標準入力から受け付ける
def create_keyword_list():
    N = int(input())
    keyword_list = []
    for i in range(N):
        keyword_list.append(input())
    print ("検索中です・・・\n")
    return keyword_list


# キーワードをミックスさせる
def mix_keywords(keyword_list):
    mixed_list = []
    for i in range(0, len(keyword_list)):
        for j in range(i + 1, len(keyword_list)):
            mixed_list.append(keyword_list[i] + '+' + keyword_list[j])
    return mixed_list

# ミックスした言葉でweb検索して結果件数を取得する
def search_keywords(mixed_list):
    mixed_dict = {}
    for w in mixed_list:
        url = "https://www.google.co.jp/search?q=" + w
        resp = web.get(url)
        resp.raise_for_status()

        soup = BeautifulSoup(resp.text, "html.parser")
        result_stats = soup.find("div", attrs={"id" : "resultStats"})
        stats_text = result_stats.text
        stats_text = stats_text.replace("約 ", "").replace(" 件", "").replace(",", "")
        mixed_dict[w] = int(stats_text)

    print ("検索ワード | 結果件数")
    for k, v in sorted(mixed_dict.items(), key=lambda x: x[1]): 
        print (str(k) + " | " + str(v))

if __name__ == '__main__':
    keyword_list = create_keyword_list()
    mixed_list = mix_keywords(keyword_list)
    search_keywords(mixed_list)

標準入力からキーワードを取得

def create_keyword_list():
    N = int(input())
    keyword_list = []
    for i in range(N):
            keyword_list.append(input())
    print ("検索中です・・・\n")
    return keyword_list

以下のように標準入力で入力したいキーワード数を入力して、
その後キーワードを入力するような流れにしています。

$ python keyword_mixer.py
3
ディズニーランド
Tシャツ
ポテトチップス
検索中です・・・

キーワードをミックスさせる

def mix_keywords(keyword_list):
        mixed_list = []
        for i in range(0, len(keyword_list)):
                for j in range(i + 1, len(keyword_list)):
                        mixed_list.append(keyword_list[i] + '+' + keyword_list[j])
        return mixed_list

入力したキーワードをリストで受けて、ミックスしたキーワードのリストを作成します。
リストの中身はこんな感じになります。

"ディズニーランド+Tシャツ"
"Tシャツ+ポテトチップス"
"ディズニーランド+ポテトチップス"

ミックスしたキーワードでGoogle検索して結果件数を取得

def search_keywords(mixed_list):
        mixed_dict = {}
        for w in mixed_list:
                url = "https://www.google.co.jp/search?q=" + w
                resp = web.get(url)
                resp.raise_for_status()

                soup = BeautifulSoup(resp.text, "html.parser")
                result_stats = soup.find("div", attrs={"id" : "resultStats"})
                stats_text = result_stats.text
                stats_text = stats_text.replace("約 ", "").replace(" 件", "").replace(",", "")
                mixed_dict[w] = int(stats_text)

        print ("検索ワード | 結果件数")
        for k, v in sorted(mixed_dict.items(), key=lambda x: x[1]):
                print (str(k) + " | " + str(v))

BeautifulSoupを使って画面から検索結果の件数を取得しています。
それを件数の少ない順にソートします。

実行結果

上記の関数を組み合わせて実行した結果がこんな感じになります。

$ python keyword_mixer.py
3
ディズニーランド
Tシャツ
ポテトチップス
検索中です・・・

検索ワード | 結果件数
ディズニーランド+Tシャツ | 42
Tシャツ+ポテトチップス | 81
ディズニーランド+ポテトチップス | 321000

とても簡単ですがいい勉強になりました。
これからもっと発展させてみます!

7
3
1

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
7
3