【Python/Selenium】DuckDuckGoで自動的にキーワード検索

Python用モジュール「Selenium」でブラウザを操作し検索エンジンDuckDuckGoで自動的にキーワード検索を行う方法についてソースコード付きでまとめました。

スポンサーリンク

DuckDuckGoで自動的にキーワード検索

Python用モジュール「Selenium」を用いて、ブラウザを操作しDuckDuckGoで自動的にキーワード検索を行ってみます。

スポンサーリンク

サンプルコード(Python3)

サンプルプログラムのソースコードです。

# -*- coding:utf-8 -*-
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

# 検索エンジンのURL:duckduckgo
url = 'https://duckduckgo.com/'

# Chromeで操作する場合
driver = webdriver.Chrome()
driver = webdriver.Chrome(executable_path='chromedriver')
driver.get(url)

# 検索ワード入力欄の要素をid名から取得
search_text_element = driver.find_element_by_xpath("//*[@id='search_form_input_homepage']")

# 検索ボタンの要素をid名から取得
search_button_element = driver.find_element_by_xpath("//*[@id='search_button_homepage']")

# 操作
actionChains = ActionChains(driver)

# 検索ワード「沖田オルタ」で検索
actionChains.send_keys_to_element(search_text_element, "沖田オルタ").click(search_button_element).perform()
関連記事
1 【Python/Selenium】ブラウザ操作入門【Python】Webスクレイピング入門Python入門 基本文法【Python】ネットワークプログラミング入門
Python
スポンサーリンク

コメント