Python google-search-consoleの検索パフォーマンスで取得したURLからページタイトルを取得する「BeautifulSoup」

'21/05/12更新:「ページ.csv」内のヘッダー名のひとつ「ページ」が「上位ページ」に変更したため、それに対応。

  Google Search Consoleは、自分のブログのアクセス状況を調べるツールです。Chromeなどのwebブラウザで操作し、「検索パフォーマンス」にある「エクスポート」>「CSVでダウンロード」で下図のようなcsvファイルを取得出来ます(但し、登録時点から蓄積されたデータです。数か月分のデータがある場合は抽出区間を指定できます。)

f:id:HK29:20201012022249p:plain

この中で「ページ.csv」ファイルには、下図のようにクリック数や表示回数、CTR(クリック率)、掲載順位など興味深いデータを得ることが出来ます。しかし、タイトルがありません。URLはあります。

f:id:HK29:20201012022600p:plain

そこで、本記事では「BeautifulSoup」を活用してURLからページのタイトルを取得して、下図のように自分のブログ内のページをランキングとした横棒グラフで可視化する雛形コードを載せました。またcsvファイルに保存します。

f:id:HK29:20201012010632j:plain

 ■本プログラム
Jupyter Labから.pyファイルに出力したのを一部編集したコードです。Anacondaプロンプトで動作確認済みです。

#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
df = pd.read_csv('ページ.csv')
df


# In[2]:


num = 15
df_head = df.head(num)
df_head


# In[3]:


import requests
from bs4 import BeautifulSoup

title_list = []
for i, url in enumerate(df_head['上位ページ'], start=1):
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    elem = soup.find("title")
    mytitle = elem.getText().split(' -')[0] 
    print(i, mytitle)
    print(url)
    title_list.append(mytitle)


# In[4]:


df_head_with_title = df_head.assign(タイトル = title_list)
df_head_with_title


# In[5]:


DF = df_head_with_title.iloc[:, [5,0,1,2,3,4]]
DF


# In[6]:


import warnings
warnings.simplefilter('ignore')
import matplotlib.pyplot as plt
#get_ipython().run_line_magic('matplotlib', 'inline')
import japanize_matplotlib
import seaborn as sns
plt.figure(figsize=(16, 10))
sns.set(style='whitegrid', font="IPAexGothic")
sns.barplot(x=df_head_with_title['クリック数'],
            y=df_head_with_title['タイトル'],
            data=df_head_with_title,
            orient = "h",
            palette=sns.color_palette('autumn', n_colors=num))
#plt.show()
plt.tight_layout()
plt.savefig("graph.png")


# In[7]:


DF.to_csv('ranking.csv', index=False, encoding='cp932')


# In[ ]:

<広告>