前言
Python 以其简洁的语法和强大的库支持,成为自动化任务和数据处理的首选语言。通过实战项目可以快速掌握核心技能。以下整理了 7 个经过调试的 Python 脚本,涵盖爬虫、AI、工具开发等领域。
环境准备
确保已安装 Python 3.6+ 及 pip。常用依赖如下:
pip install selenium requests jieba nltk pillow xlrd
注意:部分功能需申请第三方 API Key。
1. 知乎图片抓取
使用 Selenium 模拟浏览器滚动加载,提取图片链接并下载。
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import urllib.request
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.zhihu.com/question/29134042")
i = 0
while i < 10:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
try:
# 现代 Selenium 推荐写法
button = driver.find_element(By.CSS_SELECTOR, 'button.QuestionMainAction')
button.click()
print(f"page{i}")
time.sleep(1)
except Exception:
break
result_raw = driver.page_source
content_list = re.findall(r'img src="(.+?)" ', str(result_raw))
n = 0
while n < len(content_list):
timestamp = int(time.time())
local = f"{timestamp}.jpg"
urllib.request.urlretrieve(content_list[n], local)
print(f"编号:{timestamp}")
n += 1
driver.quit()


