Python网页爬虫入门教程_BeautifulSoup与requests解析

14次阅读

requests与beautifulsouppython爬虫最基础实用的组合,用于获取并解析静态网页;需安装beautifulsoup4和lxml,用r.content避免编码问题,再用soup.find/find_all提取内容。

Python网页爬虫入门教程_BeautifulSoup与requests解析

requests 获取网页内容,再用 BeautifulSoup 解析 html,是 Python 爬虫最基础也最实用的组合。它轻量、易学、够用,适合绝大多数静态页面抓取任务。

安装依赖很简单

打开终端或命令行,依次运行:

  • pip install requests
  • pip install beautifulsoup4

注意:不要装 bs4(这是旧名),要装 beautifulsoup4;如果提示缺少解析器,可额外安装 lxml(速度快)或 html.parser(Python 内置,无需安装)。

requests 获取网页源码

requests 负责“下载”,就像你在浏览器里按 F12 看到的原始 HTML。关键点有三个:

立即学习Python免费学习笔记(深入)”;

  • requests.get(url) 发起请求,返回一个 Response 对象
  • 检查 r.status_code 是否为 200,确认请求成功
  • r.text 拿到字符串形式的 HTML,或 r.content(推荐用于含中文的页面,避免编码乱码)

示例:

r = requests.get('https://httpbin.org/html') if r.status_code == 200:     html = r.content  # 更稳妥地处理编码

BeautifulSoup 解析 HTML 结构

BS4 把 HTML 字符串变成可遍历、可搜索的对象树。核心操作包括:

  • 创建解析对象:soup = BeautifulSoup(html, 'lxml')'html.parser'
  • 找单个标签:soup.find('h1')soup.h1
  • 找所有匹配项:soup.find_all('a'),支持按 class、id、属性过滤,如 soup.find_all('div', class_='post-title')
  • 提取文本:tag.get_text()tag.text(推荐前者,更健壮)
  • 提取属性:tag['href'],但需先用 if tag.has_attr('href'): 判断,避免 KeyError

实战小例子:抓取标题和链接

以一个简单博客列表页为例:

import requests from bs4 import BeautifulSoup 

url = 'https://www.php.cn/link/5fa81016250471111dfca121ae9cdc14' r = requests.get(url) soup = BeautifulSoup(r.content, 'lxml')

for article in soup.find_all('article'): title = article.find('h2') link = article.find('a') if title and link and link.has_attr('href'): print(title.get_text().strip(), '→', link['href'])

这段代码会逐个定位每篇文章区块,安全提取标题与链接,跳过缺失字段的情况。

不复杂但容易忽略细节:加 headers 模拟浏览器、控制请求频率、处理编码、检查元素是否存在——这些才是让爬虫稳定跑起来的关键。

text=ZqhQzanResources