import sys
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome import service as fs
if __name__ == "__main__":
base_url = "https://www.google.com/"
url = f"{base_url}/"
options = Options()
# Browser
CHROMEDRIVER = './chromedriver'
# ドライバー指定でChromeブラウザを開く
chrome_service = fs.Service(executable_path=CHROMEDRIVER)
driver = webdriver.Chrome(service=chrome_service)
driver.get(url)
name = "q" # elementのname
search_word = "python selenium" # 検索するワード
try:
marker = driver.find_element(By.NAME, name)
marker.send_keys(search_word)
marker.send_keys(Keys.ENTER)
xpath = "//div[@id='search']//a/h3" # 検索結果のtitleのxpath
title_elements = driver.find_elements(By.XPATH, xpath) # 結果の取得
except Exception as err:
print(err)
sys.exit(1)
for title_element in title_elements:
if len(title_element.text) > 0:
# 検索結果のtitleの親のxpathを取得
href_element = title_element.find_element(By.XPATH, "..")
# 出力
print(
f'titele={title_element.text.replace(" ...", "")} url={href_element.get_attribute("href")}'
)
time.sleep(5)
driver.close()