Requests 搜魂大法根本抓不到它们的内容!你需要先下载对应的 浏览器驱动 (Driver),比如 Chrome 的 chromedriver。
然后念动咒语,召唤傀儡:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
# 召唤 Chrome 傀儡
driver = webdriver.Chrome()
# 命令傀儡前往藏经阁 (Google/Baidu)
driver.get("https://www.python.org")
# 傀儡眼中看到的世界
print(driver.title) # "Welcome to Python.org"
你可以命令傀儡去点击、输入、寻找宝物。
# 寻找搜索框 (通过 name 属性)
search_box = driver.find_element(By.NAME, "q")
# 输入 "pycon"
search_box.send_keys("pycon")
# 模拟按下回车键
search_box.send_keys(Keys.RETURN)
# 等待页面加载 (简单粗暴法,高手用 WebDriverWait)
time.sleep(3)
# 获取结果
results = driver.find_elements(By.CSS_SELECTOR, "ul.list-recent-events li")
for res in results:
print(res.text)
# 销毁傀儡
driver.quit()
options = webdriver.ChromeOptions()
options.add_argument('--headless') # 隐身术
driver = webdriver.Chrome(options=options)
任务:Selenium 中用于定位页面元素的方法通常都在哪个子模块中?(提示:By.ID 的那个 By)