LoginSignup
1
3

More than 1 year has passed since last update.

python:seleniumとBeautifulSoupでwebスクレイピング

Posted at

・Google検索を行い、欲しいデータを取得する。

①検索ワードを入力して、GoogleChromeでGoogle検索
②表示されたWebページの下端の「他のキーワード」を取得
③「他のキーワード」をcsvデータにまとめて、保存

「テスト」という単語で検索した際に下端に表示された「他のキーワード」

screen 6.png

・目次

1.webdriver_managerのインストール
2.import
3.コード

1.webdriver_managerのインストール

seleniumで使用しているGoogleChromeのバージョンと同じChromeのドライバーを読み込ませる必要がある。
ドライバーの読み込みで苦戦したくないため、webdriver_managerを使用。

webdriver_manager
pip install webdriver_manager

参考①:https://pypi.org/project/webdriver-manager/
参考②:https://blog.n-hassy.info/2021/05/selenium-chrome-scraping/#3

2.import

必要なライブラリをimportする。

import
#1 Chromeのドライバー取得用
from webdriver_manager.chrome import ChromeDriverManager

#2 selenium
from selenium import webdriver

#3 BeautifulSoupと必要なライブラリ
from bs4 import BeautifulSoup
import requests
import time

#4 pandas
import pandas as pd

3.コード

下記の順に記述していく
①seleniumでGoogleChromeを操作して、検索を行う
②BeautifulSoupで「他のキーワード」を取得する
③pandasで結果をcsvデータに保存する

「他のキーワード」の格納先
indexs = []
result = []
webdriver
#webdriverの設定、GoogleのURLの指定
url = "https://www.google.com/"
driver = webdriver.Chrome(ChromeDriverManager().install())

#検索するワードをinput
s_word = input()
web操作(selenium,BeautifulSoup)
#検索ワードが空欄であれば終了
#検索ワードで検索を行い、ページ下端に表示される「他のキーワード」を取得
while s_word != "":

    #GoogleChromeを立ち上げ、Googleページを表示
    #検索入力箇所に検索ワードを入力して、検索(submit)ボタンを押す
    #3秒後、表示されたページのURLを取得
    driver.get(url)
    search = driver.find_element_by_name("q")
    search.send_keys(s_word)
    search.submit()
    time.sleep(3)
    url_cur = driver.current_url

    #BeautifulSoupで「他のキーワード」に表示されている単語を取得
    response = requests.get(url_cur)
    soup = BeautifulSoup(response.content,"html.parser")
    others = soup.find_all(class_="BNeawe s3v9rd AP7Wnd lRVwie")
    words = [i.text for i in others]

    #「他のキーワード」をresultに格納
    #検索ワードをindexsに格納
    result.append(words)
    indexs.append(s_word)

    #検索ワードを再入力、空白なら終了
    s_word = input()

#GoogleChromeを閉じる
driver.quit()
pandas
#検索結果をpandas のDataFrameにまとめ、csvで保存
if result != []:
    df = pd.DataFrame(result)
    df.index = indexs
    df.to_csv("other_keyword.csv")

所感

色々な単語のサジェストがわかると面白いかも!と思い、作成。
今更ですが、毎回inputで1個1個入力するのではなく、あらかじめ検索する単語を決めてfor文で進めていく方がスマートかも。

以上。

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