0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google検索にボット扱いされまくったので、Bingを使って検索ツールを作り直した話

0
Posted at

背景

まずはスケールが小さくてもいいので、Pythonで何かツールを作ってみたいと思い、検索結果を収集するPythonツールの開発に挑戦しました。

最初はGoogle検索を使って実装を試みましたが…
結論から言うと、ロボット扱いされまくって諦めました。笑

あれこれ試してもうまくいかず、最終的には Bing検索に切り替えて再構築することに。
この記事ではその試行錯誤と、最終的にできたツールについて紹介します。

🔥 Step 1:Google検索で挑戦 → Bot判定で詰む

最初はSeleniumを使ってGoogle検索結果を取得するスクリプトを作成しました。
以下は実装の一部です(一部省略):

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
import time, re, os

# Google検索ページにアクセス
URL = 'https://www.google.co.jp'
options = Options()
options.add_argument('--headless')
service = Service("/Users/m/Desktop/chromedriver")
driver = webdriver.Chrome(service=service, options=options)
driver.get(URL)
time.sleep(2)

# 検索処理(関数は省略)

が、すぐに「reCAPTCHA(私はロボットではありません)」が表示されて検索できませんでした。

試したこと

・User-Agentの偽装(複数用意)
・ランダムな待機時間の挿入(time.sleep(random.uniform(2, 5)))
・アクセス頻度の調整
・WebDriverWait の使用
・例外処理の強化

それでもBot判定を回避できず、Google検索は断念。

🔥Step 2:ChromeとChromeDriverのバージョン不一致

以下のようなエラーも出ました:

selenium.common.exceptions.SessionNotCreatedException:

・Chromeの自動アップデートと、ChromeDriverのバージョンのズレで動かず
・Chromeをバージョンアップしても、検索の安定性は変わらず…

また、セレクタが壊れやすかったため、By.CSS_SELECTORからBy.NAMEに切り替えることも検討しました。

🔥Step 3:CSV出力がうまくいかない

検索結果をCSVに出力する部分でも苦戦。
リストが空で出力されることが続き、これが地味に一番心が折れました。

試したこと

・csvモジュールのインポート(忘れてた)
・ファイルパスの指定ミス(絶対パスで修正)
・WebDriverWaitの使い方見直し
・ページの完全読み込みを待機する方法への変更
・例外処理の強化
結局、CSV出力は諦めてターミナル表示のみに変更しました。笑

🔥Step 4:Bing検索に切り替え+Tkinterでツール完成

そこでBing検索に切り替えたところ、想定通りに動作!
GUIはシンプルなターミナル型とし、Tkinterで検索キーワードを入力 → 結果表示できるようにしました。

最終的にできたツール

以下が完成コード(ターミナル用シンプル検索ツール)です:

import requests
from bs4 import BeautifulSoup
import random

user_agents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64)...",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...",
    "Mozilla/5.0 (X11; Linux x86_64)..."
]

def search_bing(keyword):
    headers = {"User-Agent": random.choice(user_agents)}
    query = keyword.replace(" ", "+")
    url = f"https://www.bing.com/search?q={query}"

    response = requests.get(url, headers=headers)
    if response.status_code != 200:
        print("検索に失敗しました")
        return []

    soup = BeautifulSoup(response.text, "html.parser")
    results = []

    for item in soup.select(".b_algo h2 a")[:3]:
        title = item.get_text()
        link = item.get("href")
        results.append((title, link))

    return results

def main():
    while True:
        keyword = input("🔍 検索キーワードを入力してください(終了: q): ")
        if keyword.lower() == 'q':
            break

        results = search_bing(keyword)
        if not results:
            print("結果が見つかりませんでした。\n")
        else:
            print(f"\n【{keyword}】の検索結果(上位3件):")
            for i, (title, link) in enumerate(results, start=1):
                print(f"{i}. {title}\n   {link}")
            print("")

if __name__ == "__main__":
    main()

👉GitHubはこちら(リポジトリ名:bing-search-keyword-helper)

📖学び&まとめ

・Google検索の自動化は難しい。Bot判定の壁が分厚すぎる。
・Seleniumでは、セレクタの安定性/タイミング制御/User-Agent偽装など細かい調整が必要。
・それよりも、“そもそも別の選択肢(Bing)を使う”ことの方が早くて賢い場合もあると学んだ。

🌼最後に

このツールは「毎回完璧に動く」とまでは言えませんが、
特定ドメインの検索順位チェックを自動化する補助ツールとしては多分実用的です。

「自動化したいけど、Googleに弾かれて困っている人」にとって、
Bingへの切り替えという選択肢があるんだなと思ってもらえたら嬉しいです🌷

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?