一、认识爬虫

爬虫(Web Crawler)是通过程序模拟浏览器行为,从互联网上自动抓取数据的技术。掌握爬虫可以帮助你自动收集信息、分析网站数据、生成数据集等。

常用的 Python 爬虫库包括:

  • requests:用于发送HTTP请求。

  • BeautifulSouplxml:用于解析HTML。

  • re:正则表达式提取内容。

  • selenium:模拟浏览器操作。

  • scrapy:专业级爬虫框架。


二、环境准备

先安装所需库:


pip install requests beautifulsoup4 lxml

验证是否安装成功:


import requests from bs4 import BeautifulSoup print("环境配置成功!")


三、最简单的网页抓取

爬虫的核心是请求与解析。


import requests url = "https://example.com" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" } response = requests.get(url, headers=headers) print(response.text[:500])

上面代码中:

  • requests.get() 用于获取网页源码。

  • headers 模拟浏览器身份防止被封。


四、解析HTML结构

用 BeautifulSoup 提取标题与文字:


from bs4 import BeautifulSoup html = response.text soup = BeautifulSoup(html, "lxml") title = soup.title.text paragraphs = [p.text for p in soup.find_all("p")] print("网页标题:", title) print("正文段落:", paragraphs[:3])

常用解析函数:

  • find(tag):查找第一个匹配标签。

  • find_all(tag):查找所有标签。

  • get("属性名"):提取属性内容,如图片URL。


五、数据提取与保存

爬虫的目标是提取有价值的信息,并保存为结构化数据。


data = [] for item in soup.find_all("a"): href = item.get("href") text = item.text.strip() if href and text: data.append({"text": text, "link": href}) import csv with open("data.csv", "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["text", "link"]) writer.writeheader() writer.writerows(data)


六、爬取多页数据

多数网站分页内容结构相似,可以使用循环控制:


import time for page in range(1, 6): url = f"https://example.com/page/{page}" response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "lxml") titles = [t.text for t in soup.find_all("h2")] print(f"第{page}页标题:", titles) time.sleep(1)

注意点:

  • time.sleep() 防止请求过快被封。

  • 避免重复抓取可使用集合去重。


七、使用正则表达式提取数据

有些网站结构复杂,用正则更高效:


import re pattern = re.compile(r'<a href="(.*?)".*?>(.*?)</a>') results = re.findall(pattern, response.text) for link, text in results: print(link, text)


八、处理动态加载网页(Selenium)

部分网站使用 JavaScript 加载数据,requests 无法直接抓取。可使用 Selenium:


from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("--headless") driver = webdriver.Chrome(options=options) driver.get("https://example.com") print(driver.page_source[:500]) driver.quit()

技巧:

  • 可配合 XPath 定位元素。

  • 模拟点击、滚动、输入等操作。


九、并发爬取加速

单线程爬虫速度慢,可以使用多线程或异步请求。

线程池示例:


from concurrent.futures import ThreadPoolExecutor urls = [f"https://example.com/page/{i}" for i in range(1, 11)] def fetch(url): r = requests.get(url, headers=headers) print("完成:", url, len(r.text)) with ThreadPoolExecutor(max_workers=5) as executor: executor.map(fetch, urls)

异步示例(aiohttp):


import asyncio import aiohttp async def fetch(session, url): async with session.get(url) as resp: text = await resp.text() print("获取:", url, len(text)) async def main(): async with aiohttp.ClientSession() as session: tasks = [fetch(session, f"https://example.com/page/{i}") for i in range(1, 6)] await asyncio.gather(*tasks) asyncio.run(main())


十、构建完整爬虫项目(实例)

示例:爬取新闻网站标题与链接。


import requests from bs4 import BeautifulSoup import csv def crawl_news(): url = "https://news.example.com" headers = {"User-Agent": "Mozilla/5.0"} res = requests.get(url, headers=headers) soup = BeautifulSoup(res.text, "lxml") news_list = [] for article in soup.find_all("article"): title = article.find("h2").text.strip() link = article.find("a").get("href") news_list.append({"title": title, "link": link}) with open("news.csv", "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["title", "link"]) writer.writeheader() writer.writerows(news_list) print("采集完成,共", len(news_list), "条新闻") if __name__ == "__main__": crawl_news()


十一、反爬与应对

网站通常会使用以下反爬策略:

反爬手段 对应解决方案
UA 检测 设置 headers
IP 限制 使用代理池
请求频率高 加延迟或限速
JS 加密 使用 selenium / 解密参数
登录验证 模拟登录、使用cookie

示例:设置代理与随机UA:


import random user_agents = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)" ] proxy_list = ["http://123.45.6.7:8080", "http://98.76.54.32:3128"] headers = {"User-Agent": random.choice(user_agents)} proxy = {"http": random.choice(proxy_list)} response = requests.get("https://example.com", headers=headers, proxies=proxy)


十二、Scrapy框架进阶

Scrapy 是专业爬虫框架,支持调度、异步、管道、去重、日志等高级功能。

创建项目:


scrapy startproject myspider cd myspider scrapy genspider example example.com

核心 spider 文件:


import scrapy class ExampleSpider(scrapy.Spider): name = "example" start_urls = ["https://example.com"] def parse(self, response): for item in response.css("a"): yield { "text": item.css("::text").get(), "url": item.attrib.get("href") }

运行:


scrapy crawl example -o data.json

Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐