一、requests 库:网络请求的利器

1. requests 简介

requests 是 Python 最常用的 HTTP 请求库,用于发送各种网络请求(GET、POST、PUT、DELETE 等)。相比内置的 urllib,它更加简单易用。

安装:

pip install requests

2. 发送请求

import requests

# 发送 GET 请求
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")

# 打印响应内容
print(response.status_code)  # 状态码,如 200 表示成功
print(response.text)         # 响应的文本内容
print(response.json())       # 如果是 JSON 数据,可直接转成字典

3. 发送 POST 请求

data = {"title": "Python", "body": "requests demo", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)
print(response.json())

4. 自定义请求头与参数

headers = {"User-Agent": "Mozilla/5.0"}
params = {"q": "python"}
response = requests.get("https://www.google.com/search", headers=headers, params=params)
print(response.url)

5. 处理异常

try:
    response = requests.get("https://example.com", timeout=5)
    response.raise_for_status()  # 检查响应是否为 200
except requests.RequestException as e:
    print("请求出错:", e)

二、BeautifulSoup:HTML 解析神器

1. BeautifulSoup 简介

BeautifulSoup 是一个强大的 HTML/XML 解析库,可以轻松提取网页中的指定数据。

安装:

pip install beautifulsoup4 lxml

2. 基本使用

from bs4 import BeautifulSoup

html = """
<html><head><title>Python 教程</title></head>
<body><h1>欢迎学习 BeautifulSoup</h1><p class='desc'>这是一个爬虫示例</p></body></html>
"""

soup = BeautifulSoup(html, "lxml")
print(soup.title.text)   # 输出:Python 教程
print(soup.h1.text)      # 输出:欢迎学习 BeautifulSoup
print(soup.find("p", class_="desc").text)  # 输出:这是一个爬虫示例

3. 常见的解析方法

# 查找第一个匹配的标签
print(soup.find("p"))

# 查找所有匹配的标签
for p in soup.find_all("p"):
    print(p.text)

# 使用 CSS 选择器
print(soup.select_one("p.desc").text)
print([a.text for a in soup.select("a.link")])

三、requests + BeautifulSoup 实战示例:爬取网页标题

import requests
from bs4 import BeautifulSoup

url = "https://quotes.toscrape.com/"
headers = {"User-Agent": "Mozilla/5.0"}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "lxml")

quotes = soup.find_all("span", class_="text")
authors = soup.find_all("small", class_="author")

for quote, author in zip(quotes, authors):
    print(f"{author.text}: {quote.text}")

运行结果(示例):

Albert Einstein: “The world as we have created it is a process of our thinking.”
J.K. Rowling: “It is our choices that show what we truly are, far more than our abilities.”

四、扩展:延伸应用

  1. 结合 pandas 将提取的数据保存为 CSV 文件:

    import pandas as pd
    df = pd.DataFrame({"author": [a.text for a in authors], "quote": [q.text for q in quotes]})
    df.to_csv("quotes.csv", index=False)
    
  2. 加入时间延迟与代理(防止被封 IP)

    import time
    import random
    time.sleep(random.uniform(1, 3))
    

总结

模块功能常用方法
requests发送 HTTP 请求get(), post(), headers, params, json()
BeautifulSoup解析 HTML/XML 文档find(), find_all(), select(), .text

这两个库是 Python 爬虫开发的入门组合,通过它们可以快速实现网页数据的采集与清洗。


本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]