Python爬虫:Requests与Beautiful Soup库详解

发布于:2025-06-30 ⋅ 阅读:(17) ⋅ 点赞:(0)

前言

在当今数据驱动的时代,网络爬虫成为了获取网络信息的重要工具。Python作为最流行的爬虫语言之一,拥有丰富的库支持。今天我们就来介绍两个最基础也最强大的爬虫库:Requests和Beautiful Soup,并补充关于lxml解析器和Requests Session的内容。

一、Requests库:让HTTP请求变得简单

Requests是一个优雅而简单的HTTP库,它让发送HTTP请求变得非常简单,比Python内置的urllib库更加人性化。

安装Requests

在开始之前,我们需要先安装Requests库:

pip install requests

基本GET请求

import requests

# 发送GET请求
response = requests.get('https://www.example.com')

# 查看响应状态码
print(response.status_code)  # 200表示成功

# 查看网页内容
print(response.text)

常用方法和属性

  1. response.status_code:HTTP请求的返回状态
  2. response.text:返回内容的文本形式
  3. response.content:返回内容的二进制形式
  4. response.json():如果返回内容是JSON格式,可以直接解析为字典
  5. response.headers:查看响应头信息

带参数的GET请求

params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url)  # 查看实际请求的URL

POST请求示例

data = {'username': 'test', 'password': '123456'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.text)

设置请求头

有些网站会检查请求头,我们可以模拟浏览器访问:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get('https://www.example.com', headers=headers)

使用Session保持会话

Requests的Session对象可以跨请求保持某些参数,比如cookies,还可以为请求方法提供缺省数据。

import requests

# 创建一个Session对象
s = requests.Session()

# 设置公共的请求头
s.headers.update({'User-Agent': 'Mozilla/5.0'})

# 登录请求(假设这是一个登录接口)
login_data = {'username': 'user', 'password': 'pass'}
s.post('https://example.com/login', data=login_data)

# 后续请求会自动携带cookies
response = s.get('https://example.com/dashboard')
print(response.text)

# Session也可以设置请求参数默认值
s.params = {'token': 'abc123'}
# 这个请求会自动加上?token=abc123
response = s.get('https://example.com/api/data')

Session的主要优势:

  1. 保持cookies,模拟用户登录状态
  2. 可以设置默认headers和params
  3. 重用TCP连接,提高请求效率
  4. 保持会话级别的设置

二、Beautiful Soup:HTML解析利器

Beautiful Soup是一个可以从HTML或XML文件中提取数据的Python库,它能够通过你喜欢的转换器实现惯用的文档导航、查找、修改文档的方式。

安装Beautiful Soup和lxml

pip install beautifulsoup4 lxml

为什么选择lxml解析器?

lxml是一个高性能的HTML/XML解析器,相比Python内置的html.parser:

  1. 速度更快
  2. 容错能力更强
  3. 支持复杂的XPath查询
  4. 更接近现代浏览器的解析方式

基本用法(使用lxml解析器)

from bs4 import BeautifulSoup
import requests

# 获取网页内容
response = requests.get('https://www.example.com')
html_content = response.text

# 创建Beautiful Soup对象,指定使用lxml解析器
soup = BeautifulSoup(html_content, 'lxml')

# 打印美化后的HTML
print(soup.prettify())

常用方法

  1. 标签选择
# 获取第一个<title>标签
print(soup.title)

# 获取<title>标签的内容
print(soup.title.string)

# 获取第一个<a>标签
print(soup.a)

# 获取所有<a>标签
all_links = soup.find_all('a')
for link in all_links:
    print(link.get('href'))
  1. 通过属性查找
# 查找id为"link1"的元素
link = soup.find(id="link1")
print(link)

# 查找所有class为"item"的div
items = soup.find_all('div', class_='item')
for item in items:
    print(item.text)
  1. CSS选择器
# 选择所有class为"article"的div下的h2标题
titles = soup.select('div.article h2')
for title in titles:
    print(title.text)
  1. XPath选择器(lxml特有)

虽然Beautiful Soup主要支持CSS选择器,但配合lxml我们可以使用XPath:

from lxml import etree

# 将Beautiful Soup对象转换为lxml的etree
tree = etree.HTML(str(soup))

# 使用XPath选择元素
results = tree.xpath('//div[@class="article"]//h2/text()')
for result in results:
    print(result)

实际示例:爬取简单新闻标题(使用lxml解析器)

import requests
from bs4 import BeautifulSoup

# 发送请求
url = 'https://news.sina.com.cn/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers)

# 解析HTML,使用lxml解析器
soup = BeautifulSoup(response.text, 'lxml')

# 提取新闻标题 - 这里的选择器需要根据实际网页结构调整
news_titles = soup.select('.news-item h2 a')
for i, title in enumerate(news_titles[:10], 1):
    print(f"{i}. {title.text.strip()}")

三、Requests和Beautiful Soup配合使用

让我们看一个完整的例子,爬取豆瓣电影Top250,使用Session和lxml解析器:

import requests
from bs4 import BeautifulSoup
import time

def scrape_douban_top250():
    # 创建Session对象
    s = requests.Session()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }
    s.headers.update(headers)
    
    for start in range(0, 250, 25):
        url = f'https://movie.douban.com/top250?start={start}'
        
        try:
            response = s.get(url)
            response.raise_for_status()  # 检查请求是否成功
            
            # 使用lxml解析器
            soup = BeautifulSoup(response.text, 'lxml')
            items = soup.select('.item')
            
            for item in items:
                title = item.select_one('.title').text
                rating = item.select_one('.rating_num').text
                print(f"电影: {title} | 评分: {rating}")
            
            # 礼貌性延迟
            time.sleep(2)
            
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            break

scrape_douban_top250()

四、注意事项

  1. 遵守robots.txt:在爬取任何网站前,先检查其robots.txt文件,了解哪些内容允许爬取
  2. 设置延迟:在循环请求中添加time.sleep(2)等延迟,避免给服务器造成压力
  3. 异常处理:网络请求可能会失败,添加try-except块处理异常
  4. 用户代理:合理设置User-Agent,模拟浏览器行为
  5. 合法性:确保你的爬虫行为符合法律法规和网站的使用条款
  6. 解析器选择
    • 对于简单任务,html.parser足够
    • 对于复杂或大型HTML文档,推荐使用lxml
    • 如果需要处理不规范HTML,可以尝试html5lib(但速度较慢)

五、总结

本文介绍了Python爬虫的两个基础库:

  1. Requests

    • 简单易用的HTTP请求库
    • Session对象可以保持cookies和会话状态
    • 支持各种HTTP方法和参数设置
  2. Beautiful Soup

    • 强大的HTML/XML解析库
    • 配合lxml解析器性能更佳
    • 提供多种查找和遍历文档树的方法

两者的配合使用流程通常是:

  1. 使用Requests获取网页内容
  2. 使用Beautiful Soup解析和提取数据
  3. 对提取的数据进行处理和存储

随着需求的复杂化,你可能还需要学习:

  1. Scrapy框架:更强大、更专业的爬虫框架
  2. Selenium:处理JavaScript渲染的页面
  3. 正则表达式:更灵活的数据提取方式

最后记住,爬虫虽好,但要合法合规使用哦!


创作不易,如果您都看到这里了,可以给我一个点赞、收藏并关注一下么?您的支持与喜爱是激励我创作的最大动力!

如果内容有误请及时联系我进行修改


网站公告

今日签到

点亮在社区的每一天
去签到