python3.6.5爬虫教程

python3.6.5爬虫教程
最新回答
|欧巴桑_

2026-06-07 01:45:19

以下是针对Python 3.6.5爬虫的详细教程,涵盖基础概念、核心库使用及完整示例:

一、爬虫基础概念

爬虫定义:自动访问网站、提取数据的程序,本质是通过HTTP协议与网页交互,解析返回内容(HTML/JSON等)获取结构化信息。

二、核心库详解1. Requests库(HTTP请求)import requests# 基础GET请求response = requests.get('
https://www.example.com'
)print(response.status_code) # 查看状态码print(response.text[:200]) # 打印前200字符# 带参数的请求params = {'key1': 'value1', 'key2': 'value2'}response = requests.get('
https://httpbin.org/get'
, params=params)print(response.json()) # 解析JSON响应# 处理异常try: response = requests.get('
https://invalid-url.com'
, timeout=5) response.raise_for_status() # 非200状态码抛出异常except requests.exceptions.RequestException as e: print(f"请求失败: {e}")2. BeautifulSoup(HTML解析)from bs4 import BeautifulSouphtml = """<html> <head><title>测试页面</title></head> <body> <h1 class="title">主标题</h1> <a href="/link1">链接1</a> <a href="/link2">链接2</a> </body></html>"""soup = BeautifulSoup(html, 'html.parser')# 元素提取title = soup.title.text # 获取标题文本h1 = soup.find('h1', class_='title').text # 按标签和属性查找links = [a['href'] for a in soup.find_all('a')] # 获取所有链接print(f"标题: {title}")print(f"H1内容: {h1}")print(f"所有链接: {links}")3. Selenium(动态页面控制)from selenium import webdriverfrom selenium.webdriver.chrome.service import Servicefrom selenium.webdriver.common.by import By# 配置Chrome驱动(需提前下载对应版本驱动)service = Service('./chromedriver') # 驱动路径driver = webdriver.Chrome(service=service)try: driver.get('
https://www.baidu.com'
) search_box = driver.find_element(By.ID, 'kw') search_box.send_keys('Python爬虫') search_box.submit() # 等待结果加载(显式等待更推荐) import time time.sleep(3) print("当前页面标题:", driver.title)finally: driver.quit() # 必须关闭浏览器4. Scrapy框架(高级爬虫)

项目结构:

myproject/ scrapy.cfg myproject/ __init__.py items.py # 定义数据结构 pipelines.py # 数据处理管道 settings.py # 全局配置 spiders/ # 爬虫目录 __init__.py example_spider.py

示例爬虫代码:

# spiders/example_spider.pyimport scrapyclass ExampleSpider(scrapy.Spider): name = 'example' start_urls = ['
https://quotes.toscrape.com/'
] def parse(self, response): for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').get(), 'author': quote.css('small.author::text').get(), 'tags': quote.css('div.tags a.tag::text').getall(), } # 翻页处理 next_page = response.css('li.next a::attr(href)').get() if next_page: yield response.follow(next_page, self.parse)

运行命令:

scrapy crawl example -o quotes.json # 输出为JSON文件三、完整实战案例

目标:爬取豆瓣电影Top250的标题和评分

import requestsfrom bs4 import BeautifulSoupimport csvdef scrape_douban_top250(): base_url = "
https://movie.douban.com/top250"
headers = {'User-Agent': 'Mozilla/5.0'} with open('douban_top250.csv', 'w', encoding='utf-8-sig', newline='') as f: writer = csv.writer(f) writer.writerow(['排名', '标题', '评分', '评价人数']) for start in range(0, 250, 25): # 分页处理 url = f"{base_url}?start={start}" response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') for item in soup.find_all('div', class_='item'): rank = item.find('em').text title = item.find('span', class_='title').text rating = item.find('span', class_='rating_num').text votes = item.find('div', class_='star').find_all('span')[-1].text[:-3] writer.writerow([rank, title, rating, votes]) print(f"已爬取: {title} ({rating})")if __name__ == '__main__': scrape_douban_top250()四、关键注意事项
  1. 合法性:遵守robots.txt协议,添加User-Agent,控制请求频率(建议2-5秒/次)
  2. 反爬策略:

    使用Session保持会话

    处理cookies

    随机延迟(time.sleep(random.uniform(1,3)))

  3. 性能优化:

    使用连接池(requests.Session())

    异步请求(考虑aiohttp或Scrapy)

  4. 数据存储:

    结构化数据:CSV/JSON/SQLite

    大规模数据:MongoDB/MySQL

五、学习资源推荐
  1. 官方文档:

    Requests文档

    BeautifulSoup文档

    Scrapy官方教程

  2. 进阶方向:

    分布式爬虫(Scrapy-Redis)

    验证码识别(Tesseract/打码平台)

    APP数据抓取(mitmproxy/Appium)

通过以上内容,您可以系统掌握Python 3.6.5环境下的爬虫开发技术,从简单页面抓取到复杂框架应用均可覆盖。实际开发中建议先分析目标网站结构,再选择合适的工具组合。