Python転職初心者向けエンジニアリングブログ

Pythonに魅了されたあなたへ。エンジニアリングの扉を開く転職初心者向けのブログへようこそ。このブログでは、Pythonの奥深さに迫りながら、エンジニアリングへの転職に役立つ情報を提供しています。未経験者から始めるPythonエンジニアリングの世界への一歩を踏み出すためのガイダンス、ベストプラクティス、そして成功事例など、初心者の方でもわかりやすいコンテンツをお届けします。

Pythonを使用してサイトマップを検出し、Googleに自動登録する方法

LYPプレミアム会員 python

検索エンジンにサイトを効果的に登録するためには、サイトマップ(Sitemap)の提出が重要です。Googleなどの主要な検索エンジンは、サイトマップを利用してサイト内のページをクロールしやすくし、検索結果に正確に反映させることができます。この記事では、Pythonを使用してサイトマップを検出し、Googleに自動登録する手法について詳しく解説します。

サイトマップの検出

サイトマップを検出するためには、サイト上のHTMLやrobots.txtを解析し、サイトマップのURLを見つける必要があります。Pythonでは、Beautiful SoupやRequestsといったライブラリを使用してこれを行うことができます。

必要なライブラリのインストール

まず初めに、必要なライブラリをインストールします。

pip install requests beautifulsoup4

サイトマップの検出コード

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

def find_sitemap(url):
    try:
        # サイトのHTMLを取得
        response = requests.get(url)
        response.raise_for_status()

        # HTMLを解析
        soup = BeautifulSoup(response.text, 'html.parser')

        # robots.txtからサイトマップのURLを取得
        robots_url = urljoin(url, '/robots.txt')
        robots_response = requests.get(robots_url)
        robots_response.raise_for_status()
        robots_content = robots_response.text

        # robots.txt内でサイトマップが指定されている場合、それを取得
        sitemap_start = robots_content.find('Sitemap:')
        if sitemap_start != -1:
            sitemap_end = robots_content.find('\n', sitemap_start)
            sitemap_url = robots_content[sitemap_start + 8:sitemap_end].strip()
            return sitemap_url

        # HTML内のサイトマップリンクを取得
        sitemap_links = soup.find_all('a', href=lambda href: (href and 'sitemap' in href.lower()))
        if sitemap_links:
            return urljoin(url, sitemap_links[0]['href'])

    except requests.RequestException as e:
        print(f"Error: {e}")

    return None

# 使用例
site_url = 'https://example.com'
sitemap_url = find_sitemap(site_url)

if sitemap_url:
    print(f"Found Sitemap: {sitemap_url}")
else:
    print("Sitemap not found.")

上記のコードでは、指定したサイトのHTMLとrobots.txtを解析し、サイトマップのURLを見つける関数find_sitemapを定義しています。robots.txt内で指定されている場合はそれを優先し、指定がない場合はHTML内のリンクを探します。最終的に見つかったサイトマップのURLを返します。

Googleサイトマップを自動登録する

Googleサイトマップを登録するには、Google Search Consoleを使用します。Search ConsoleにGoogleアカウントでログインし、サイトを追加した後、サイトのプロパティに移動してサイトマップを追加します。

Google APIクライアントライブラリのインストール

pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib

Google Search Console APIを使用してサイトマップを登録

from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# Google Search Console APIのスコープ
SCOPES = ['https://www.googleapis.com/auth/webmasters']

# サイトマップのURL
sitemap_url = 'https://example.com/sitemap.xml'

def get_credentials():
    creds = None

    # トークンファイルの作成・読み込み
    token_file = 'token.json'
    if os.path.exists(token_file):
        creds = Credentials.from_authorized_user_file(token_file)

    # トークンが無効または存在

しない場合は再認証
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            # 新しいトークンを取得
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)

        # トークンを保存
        with open(token_file, 'w') as token:
            token.write(creds.to_json())

    return creds

def submit_sitemap(service, site_url, sitemap_url):
    request_body = {
        "siteUrl": site_url,
        "feedpath": sitemap_url
    }

    try:
        # サイトマップの提出リクエスト
        request = service.sitemaps().submit(siteUrl=site_url, feedpath=sitemap_url)
        response = request.execute()

        if response.get('error'):
            print(f"Error submitting sitemap: {response['error']['message']}")
        else:
            print("Sitemap submitted successfully.")

    except Exception as e:
        print(f"Error: {e}")

# Google Search Console APIのサービスオブジェクトを取得
credentials = get_credentials()
service = build('webmasters', 'v3', credentials=credentials)

# サイトマップの提出
submit_sitemap(service, site_url, sitemap_url)

上記のコードでは、Google Search Console APIを使用してサイトマップを自動的に登録するためのスクリプトを示しています。Google APIクライアントライブラリを使用して認証し、Search Console APIのサービスオブジェクトを作成します。その後、サイトマップの提出リクエストを送信し、登録の成否を確認します。

まとめ

この記事では、Pythonを使用してサイトマップを検出し、Google Search Console APIを利用してサイトマップを自動登録する手法について詳しく解説しました。サイトマップの提出は検索エンジンにとって重要なステップであり、これによってサイト内のページが効果的にクロールされ、正確に検索結果に反映されます。Pythonを使用することで、これらの手順を効率的に実行できます。