LoginSignup
1
1

More than 5 years have passed since last update.

[python]Google検索結果で、自分のサイトが何番目か調べる .py

Posted at

私のサイトは検索結果上位に表示されてるの? 何位なの?

というわけで、自分のサイトが何番目に表示されているのかを知りたいな、と思い前回の内容を改修しました。

内容

検索結果のリストを保持するのは変えず、
  ① URLだけのリストを作成
  ② キーワードを含むURLを抜き出し別のリストをつくる
  ③ indexでもともとのリストの何番目にあるのかを確認する
という非常にアナログな方法で解決しました。
(リスト内を部分一致で検索し、それが何番目かを直接引っ張る方法はなさそうでした。)

成果物

以下を
python googlerank.py 検索語
で実行してください
引数がないと機能しません。

googlerank.py

# -*- coding: utf-8 -*-
import requests
import sys
from bs4 import BeautifulSoup
import csv
from datetime import datetime
date = datetime.now().strftime("%Y/%m/%d %H:%M:%S")

# エリアはus、言語はenglish、検索件数は10件  で検索
google = 'https://www.google.com/search?gl=us&hl=en&num=10&q='
resp = requests.get(google+ ''.join(sys.argv[1:]))
soup = BeautifulSoup(resp.text, "lxml")

# 初期値
newlist=[]
rank='NONE'

# キーワード;知りたいサイトのドメインにして遊んでください
keyword = 'keyword'


elems = soup.select(".r a")

with open('googlesearch.csv', 'w', newline='') as f:
        f.write("")

for elem in elems:
    txtelem = elem.getText()
    repelem = elem.get('href').replace('/url?q=','')
#  csvに書き込む内容を確認したい場合は次をコメントアウトしてください
#    print('{} ,{}'.format(txtelem, repelem))
    data = [[elem.getText(),repelem]]
    with open('googlesearch.csv', 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerows(data)
    newlist.append(repelem)

l_in = [s for s in newlist if keyword in s]
if l_in ==[]:
        print('There is no URL')

else:
        print(keyword + ' is indexed')
        for i in range(len(l_in)):
                rank = newlist.index(str(l_in[i]))
                print(rank)
data2 = [[date ,rank]]
with open('googlerank.csv', 'a', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(data2)

実行結果が表示され、同時にcsvファイルが同一ディレクトリにできますので、確認して下さい。
csvが不要でしたら、 with ~ を削除してください。

毎朝実行して、データを蓄積することにしましょう。

1
1
0

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