DukeDuke
主页
文档转换
关于我们
主页
文档转换
关于我们
  • 什么是Python
  • Python简介
  • Python安装
  • Python基础语法
  • Python数据类型
  • Python数字
  • Python字符串
  • Python列表
  • Python元组
  • Python字典
  • Python日期时间
  • Python文件操作
  • Python异常处理
  • Python函数
  • Python类
  • Python模块
  • Python包
  • Python多线程
  • Python面向对象
  • Python爬虫
  • Django web框架

Python 爬虫

什么是爬虫?

爬虫就像是一个自动化的"网络收集员",它会自动访问网页,把网页上的信息(比如文字、图片、链接等)抓取下来,然后保存到本地或者数据库里。就像你手动复制网页内容一样,但是爬虫可以自动完成,而且速度很快。

为什么需要爬虫?

  • 数据收集:比如收集商品价格、新闻资讯、股票数据等
  • 信息监控:监控网站更新、价格变化等
  • 数据分析:为后续的数据分析提供原始数据
  • 自动化测试:测试网站功能是否正常

常用的 Python 爬虫库

1. requests - 发送 HTTP 请求

这是最基础的库,用来向网站发送请求获取网页内容。

import requests

# 获取网页内容
response = requests.get('https://www.baidu.com')
print(response.text)  # 打印网页的HTML内容

2. BeautifulSoup - 解析 HTML

用来解析网页的 HTML 结构,提取我们需要的信息。

from bs4 import BeautifulSoup
import requests

# 获取网页
response = requests.get('https://www.baidu.com')
soup = BeautifulSoup(response.text, 'html.parser')

# 找到所有链接
links = soup.find_all('a')
for link in links:
    print(link.get('href'))

3. Scrapy - 专业爬虫框架

功能强大的爬虫框架,适合大规模爬取。

实际案例

案例 1:爬取天气信息

import requests
from bs4 import BeautifulSoup
import json

def get_weather():
    """爬取北京天气信息"""
    url = "http://www.weather.com.cn/weather/101010100.shtml"

    # 设置请求头,模拟浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }

    try:
        # 发送请求
        response = requests.get(url, headers=headers)
        response.encoding = 'utf-8'  # 设置编码

        # 解析HTML
        soup = BeautifulSoup(response.text, 'html.parser')

        # 找到天气信息
        weather_div = soup.find('div', class_='weather')
        if weather_div:
            temperature = weather_div.find('span', class_='temperature').text
            weather_desc = weather_div.find('span', class_='weather-desc').text

            print(f"北京天气:{weather_desc}")
            print(f"温度:{temperature}")
        else:
            print("未找到天气信息")

    except Exception as e:
        print(f"爬取失败:{e}")

# 运行爬虫
get_weather()

案例 2:爬取新闻标题

import requests
from bs4 import BeautifulSoup
import time

def get_news_titles():
    """爬取新浪新闻首页的新闻标题"""
    url = "https://news.sina.com.cn/"

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }

    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = 'utf-8'

        soup = BeautifulSoup(response.text, 'html.parser')

        # 找到新闻标题(这里需要根据实际网站结构调整选择器)
        news_titles = soup.find_all('h1', class_='news-title')

        print("今日新闻标题:")
        for i, title in enumerate(news_titles[:10], 1):  # 只显示前10条
            print(f"{i}. {title.text.strip()}")

    except Exception as e:
        print(f"爬取失败:{e}")

get_news_titles()

案例 3:爬取图片并保存

import requests
import os
from urllib.parse import urljoin

def download_images():
    """下载网页中的图片"""
    url = "https://example.com"  # 替换为实际网站

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }

    try:
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')

        # 找到所有图片
        images = soup.find_all('img')

        # 创建保存目录
        if not os.path.exists('downloaded_images'):
            os.makedirs('downloaded_images')

        for i, img in enumerate(images):
            img_url = img.get('src')
            if img_url:
                # 处理相对URL
                if not img_url.startswith('http'):
                    img_url = urljoin(url, img_url)

                # 下载图片
                img_response = requests.get(img_url, headers=headers)

                # 保存图片
                filename = f"downloaded_images/image_{i}.jpg"
                with open(filename, 'wb') as f:
                    f.write(img_response.content)

                print(f"已下载:{filename}")

    except Exception as e:
        print(f"下载失败:{e}")

# download_images()  # 取消注释运行

爬虫的基本步骤

  1. 分析目标网站:了解网站结构,找到需要的数据在哪里
  2. 发送请求:使用 requests 库向网站发送 HTTP 请求
  3. 解析数据:使用 BeautifulSoup 解析 HTML,提取需要的信息
  4. 保存数据:将数据保存到文件或数据库
  5. 处理异常:处理网络错误、解析错误等异常情况

重要注意事项

1. 遵守 robots.txt

每个网站都有 robots.txt 文件,告诉爬虫哪些页面可以爬取,哪些不可以。要遵守这个规则。

import requests

def check_robots_txt(url):
    """检查网站的robots.txt"""
    robots_url = url + '/robots.txt'
    try:
        response = requests.get(robots_url)
        print("robots.txt内容:")
        print(response.text)
    except:
        print("无法获取robots.txt")

2. 设置请求间隔

不要频繁请求,会给服务器造成压力。建议每次请求之间间隔 1-3 秒。

import time

def polite_crawler():
    """有礼貌的爬虫"""
    urls = ['url1', 'url2', 'url3']

    for url in urls:
        # 发送请求
        response = requests.get(url)
        # 处理数据...

        # 等待2秒再请求下一个
        time.sleep(2)

3. 使用请求头

模拟真实浏览器访问,避免被网站识别为爬虫。

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate',
    'Connection': 'keep-alive',
}

4. 异常处理

网络请求可能失败,要做好异常处理。

def safe_request(url):
    """安全的请求函数"""
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()  # 检查HTTP状态码
        return response
    except requests.exceptions.Timeout:
        print("请求超时")
    except requests.exceptions.RequestException as e:
        print(f"请求失败:{e}")
    except Exception as e:
        print(f"未知错误:{e}")
    return None

进阶技巧

1. 使用代理

如果 IP 被限制,可以使用代理。

proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}

response = requests.get(url, proxies=proxies)

2. 处理 JavaScript 渲染的页面

有些网站的内容是通过 JavaScript 动态加载的,需要使用 Selenium。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def get_js_content(url):
    """获取JavaScript渲染后的内容"""
    chrome_options = Options()
    chrome_options.add_argument('--headless')  # 无界面模式

    driver = webdriver.Chrome(options=chrome_options)
    driver.get(url)

    # 等待页面加载
    time.sleep(3)

    content = driver.page_source
    driver.quit()

    return content

3. 数据存储

将爬取的数据保存到文件或数据库。

import json
import csv

def save_data(data, filename='data.json'):
    """保存数据到JSON文件"""
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def save_to_csv(data, filename='data.csv'):
    """保存数据到CSV文件"""
    with open(filename, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['标题', '链接', '时间'])  # 表头
        for item in data:
            writer.writerow([item['title'], item['link'], item['time']])

总结

Python 爬虫是一个强大的工具,可以帮助我们自动化收集网络信息。但是要记住:

  1. 合法合规:遵守网站的使用条款和 robots.txt
  2. 有礼貌:不要频繁请求,给服务器留出休息时间
  3. 有技术:使用合适的库和技巧,提高爬取效率
  4. 有备份:做好异常处理,避免程序崩溃

通过以上案例和技巧,你就可以开始你的爬虫之旅了!记住,爬虫技术要用于正当用途,不要做违法的事情。

最近更新:: 2026/4/17 13:21
Contributors: Duke
Prev
Python面向对象
Next
Django web框架