banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

Pythonを使用して、ランキング検索を一括で行うツールを開発します。

最近、Google SEOQ(検索エンジン最適化)を使用する必要があり、それを知っている友人たちは、SEO にはキーワードの検索順位を調べることが不可欠であることを知っているはずです。キーワードが少ない場合は、1 つずつ調べることは問題ありませんが、後半になると、1 つのウェブサイトには数百から数千のキーワードがありますので、1 人で調べると数時間かかります。

市場には多くの無料または有料の SEO ツールがありますが、無料のものは基本的に一括検索できません。オンラインで最大 10 個のクエリしかできないものもありますし、クエリの速度も遅いです。

有料のツール、例えば Ahrefs や SEMrush は、月単位で最低 995 ドルの料金がかかりますが、適切なツールと考えるなら購入することもできます。なぜなら、これらのツールの多くの機能は非常に実用的だからです。今日は、Python をベースにしたこのランキング検索ツールを皆さんと共有しますが、もちろん何の費用もかかりません。Python の開発環境をインストールするだけです。

実装手順
言葉を多くせずに、コードを書きましょう。

import requests
from bs4 import Beautifulsoup

まず、requests と Beautifulsoup の 2 つのライブラリをインポートします。requests は HTTP リクエストを送信するために、Beautifulsoup は HTML を解析するために使用されます。

python
def get_google_rank(keyword, website):
    try:
        url = f"https://www.google.com/search?q={keyword}"
        headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36'}
        response = requests.get(url, headers=headers)
        response.raise_for_status()

        soup = BeautifulSoup(response.text, 'html.parser')
        search_results = soup.find_all('div', class_='g')

        for i, result in enumerate(search_results):
            link = result.find('a')['href']
            if website in link:
                return i + 1  # ランキングを返す(1から開始)
        
        return -1  # ウェブサイトが見つからない場合は-1を返す

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")
        return None

上記のコードは、get_google_rank という名前の関数を定義しています。この関数は 2 つの引数、キーワード(keyword)とウェブサイト(website)を受け取ります。関数の目的は、指定されたキーワードの Google 検索結果での順位を取得することです。

関数内部では、まず指定されたキーワードを使用して Google 検索の URL を構築します。次に、User-Agent ヘッダーを設定して、ブラウザのリクエストを模倣し、requests.get メソッドを使用して HTTP リクエストを送信し、検索結果ページのレスポンスを取得します。response.raise_for_status () は、リクエストが成功したかどうかをチェックし、ステータスコードが 200 でない場合は例外を発生させます。

次に、Beautifulsoup ライブラリを使用してレスポンスの HTML コンテンツを解析し、Beautifulsoup オブジェクトを作成し、html.parser パーサーを使用して解析します。その後、class 属性が "g" である div 要素をすべて検索結果として検索します。

次に、enumerate 関数を使用して検索結果リストを反復処理し、result.find ('a')['href'] を使用して各検索結果のリンクを取得します。指定されたウェブサイトのドメインがリンクに含まれている場合、現在の順位(1 から数える)を返します。

ループが終了した後、指定されたウェブサイトのドメインが見つからなかった場合、関数は - 1 を返し、ウェブサイトが見つからなかったことを示します。

リクエストの過程で例外が発生した場合、requests.exceptions.RequestException 例外が発生し、エラーメッセージが表示され、None が返されます。

# 使用例
keywords = ['摸鱼小游戏','是男人就下100层','游戏']
website = 'haiyong.site'

for keyword in keywords:
    rank = get_google_rank(keyword, website)
    if rank is not None:
        if rank == -1:
            print(f"{keyword}没有排名")
        else:
            print(f"{keyword}排名第{rank}")

最後に、使用例のコードがあります。キーワードのリストである keywords と指定されたウェブサイトのドメインである website を定義しています。

for ループを使用してキーワードリストを反復処理し、get_google_rank 関数を呼び出して、Google 検索結果での各キーワードの順位を取得します。返された順位が None でない場合、順位の値に基づいて条件分岐を行い、順位が - 1 の場合はキーワードに順位がないことを示すメッセージを表示し、それ以外の場合はキーワードの順位情報を表示します。

以上がコードの意味とロジックです。このコードは、指定されたキーワードの Google 検索結果での順位を取得し、この関数の使用方法を示す例を提供しています。

完全なコード#

import requests
from bs4 import BeautifulSoup

def get_google_rank(keyword, website):
    try:
        url = f"https://www.google.com.hk/search?q={keyword}"
        headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36'}
        response = requests.get(url, headers=headers)
        response.raise_for_status()

        soup = BeautifulSoup(response.text, 'html.parser')
        search_results = soup.find_all('div', class_='g')

        for i, result in enumerate(search_results):
            link = result.find('a')['href']
            if website in link:
                return i + 1  # ランキングを返す(1から開始)
        
        return -1  # ウェブサイトが見つからない場合は-1を返す

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")
        return None

# 使用例
keywords = ['摸鱼小游戏','是男人就下100层','游戏']
website = 'haiyong.site'

for keyword in keywords:
    rank = get_google_rank(keyword, website)
    if rank is not None:
        if rank == -1:
            print(f"{keyword}没有排名")
        else:
            print(f"{keyword}排名第{rank}")

Bing での検索結果のスクリーンショットを載せます。

image

image

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。