import requests
from bs4 import BeautifulSoup
# print(BeautifulSoup)
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
# 初始化 WebDriver
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
# 創建 WebDriver 實例(這裡以 Chrome 為例)
driver = webdriver.Chrome()
# 檢查 WebDriver 版本
print(f'webdriver __version__:{webdriver.__version__}')
try:
# 1. 連線到 Google
url = "https://www.google.com.tw/webhp?hl=zh-TW&cr=countryTW"
driver.get(url)
time.sleep(2) # 等待頁面載入
# 2. 找到搜尋框並輸入關鍵字
search_box = driver.find_element(By.ID, "APjFqb")
search_box.send_keys("泰國") # 輸入關鍵字
search_box.send_keys(Keys.RETURN) # 模擬按下 Enter
time.sleep(2) # 等待搜尋結果載入
# 3. 擷取第一頁的標題和連結
results = driver.find_elements(By.XPATH, '//h3[@class="LC20lb MBeuO DKV0Md"]')
for result in results:
title = result.text
link_element = result.find_element(By.XPATH, "..") # 找到 h3 的父節點 a
link = link_element.get_attribute("href")
print(f"標題: {title}\n連結: {link}\n")
finally:
# 關閉瀏覽器
driver.quit()