首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python 爬虫入门:从零抓取网页数据

Python 爬虫入门:从零抓取网页数据

原创
作者头像
用户12890632
发布于 2026-11-11 15:23:40
发布于 2026-11-11 15:23:40
2740
举报

网络爬虫本质上就是用程序模拟浏览器访问网页,然后把页面中我们需要的内容提取出来。对于初学者来说,不必一开始就追求复杂框架,可以先掌握 发送请求、解析页面、保存数据 这三个核心步骤。

下面以抓取一个包含标题列表的网页为例,演示如何编写一个简单的 Python 爬虫。

一、环境准备

需要先安装两个常用库:

代码语言:javascript
复制
pip install requests beautifulsoup4

其中:

  • requests 用于发送网络请求;
  • BeautifulSoup 用于解析 HTML 页面内容。

二、完整示例代码

代码语言:javascript
复制
import requests
from bs4 import BeautifulSoup

def fetch_page(url: str) -> str:
    """获取网页内容"""
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                      "AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/120.0.0.0 Safari/537.36"
    }
    response = requests.get(url, headers=headers, timeout=10)
    response.encoding = response.apparent_encoding
    response.raise_for_status()
    return response.text

def parse_titles(html: str) -> list[str]:
    """从网页中解析标题"""
    soup = BeautifulSoup(html, "html.parser")

    # 这里以常见的 h2 标题为例,实际需要根据目标网页结构调整
    titles = []
    for tag in soup.find_all("h2"):
        text = tag.get_text(strip=True)
        if text:
            titles.append(text)

    return titles

def save_to_file(titles: list[str], filename: str = "titles.txt") -> None:
    """将结果保存到文件"""
    with open(filename, "w", encoding="utf-8") as f:
        for title in titles:
            f.write(title + "\n")

def main():
    url = "https://wlt.jogonsoft.com/"  # 示例练习网站
    print(f"正在抓取:{url}")

    html = fetch_page(url)
    titles = parse_titles(html)

    if titles:
        for i, title in enumerate(titles, 1):
            print(f"{i}. {title}")

        save_to_file(titles)
        print(f"\n共抓取 {len(titles)} 条内容,已保存到 titles.txt")
    else:
        print("未找到标题,请检查网页结构是否正确。")

if __name__ == "__main__":
    main()

三、代码说明

模块

作用

fetch_page

发送 HTTP 请求,获取网页 HTML

parse_titles

使用 BeautifulSoup 解析页面,提取目标内容

save_to_file

把抓取结果写入本地文件

main

组织整个爬虫流程

示例中抓取的是练习网站,实际使用时需要把 parse_titles 中的选择器改成目标网页的真实结构。例如,如果目标内容在 div.quote 中,可以这样写:

代码语言:javascript
复制
for item in soup.select("div.quote"):
    text = item.select_one("span.text")
    author = item.select_one("small.author")
    if text and author:
        print(text.get_text(strip=True))
        print(author.get_text(strip=True))

四、注意事项

  1. 遵守网站规则:抓取前查看网站的 robots.txt 和使用条款。
  2. 控制请求频率:不要短时间内频繁请求,避免给服务器造成压力。
  3. 不要抓取敏感数据:包括个人隐私、付费内容、受版权保护的数据等。
  4. 处理异常情况:网络请求可能失败,应做好超时、重试和错误处理。
  5. 动态网页需要额外处理:如果页面数据通过 JavaScript 加载,可能需要使用 Selenium、Playwright 或分析接口请求。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 一、环境准备
  • 二、完整示例代码
  • 三、代码说明
  • 四、注意事项
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档