安装 selenium 模块和 Chrome 浏览器驱动

步骤:

  1. 安装 Selenium 模块:
pip install selenium
  1. 下载浏览器驱动(下载即可,无需安装,使用时要指定它的路径):请参考 https://selenium-python.readthedocs.io/installation.html#drivers,本文使用 Chrome 浏览器,注意下载与浏览器对应的版本。

快速入门示例代码

本示例以爬取本人博客为例(输出格式:“- 日期: [博文标题](博文链接URL)”):

import re
from selenium import webdriver

driver = webdriver.Chrome(r"E:\test\chromedriver_79.0.3945.36_win32\chromedriver.exe")    # 这里指定前面下载的浏览器驱动路径
# driver.maximize_window()
url = ''
driver.get(url)
page = 1
while True:
    print("Page %d: %s" % (page, url))
    articles = driver.find_elements_by_css_selector("a.postTitle2")
    desc = driver.find_elements_by_css_selector("div.postDesc")
    assert len(articles) == len(desc)
    for a, d in zip(articles, desc):
        href = a.get_attribute("href")
        title = a.get_attribute("innerHTML").strip()
        date = re.search("(\d{4}-\d{2}-\d{2})", d.get_attribute("innerHTML")).group(1)
        print("- %s: [%s](%s)" % (date, title, href))
    next = driver.find_element_by_id("nav_next_page").get_attribute("innerHTML")
    url = None
    if re.search("href", next):
        url = re.search('href="(\S+)"', next).group(1)
    else:
        next = driver.find_element_by_id("homepage_bottom_pager").get_attribute("innerHTML")
        matched = re.search('href="(\S+)">下一页<', next)
        if matched:
            url = matched.group(1)
    if not url:
        print("No next page, exit")
        break
    driver.get(url)
    page += 1
driver.close()