初学者如何用 Python 写第一个爬虫?

如果你是 Python 初学者,写第一个爬虫其实并不复杂。核心思路是:获取网页 → 解析网页 → 提取数据。下面是一套最简单的入门步骤。


一、什么是爬虫

网络爬虫(Web Crawler)
程序自动访问网页,并从网页中提取信息。

常见用途:

  • 抓取新闻
  • 获取商品价格
  • 收集数据做分析

二、爬虫基本流程

爬虫一般分为 4 步:

发送请求
↓
获取网页HTML
↓
解析HTML
↓
提取数据


三、准备环境

建议先安装两个常用库:

  • Requests
  • Beautiful Soup

安装:

pip install requests
pip install beautifulsoup4


四、第一步:获取网页

使用 Requests 发送请求。

示例:

import requests

url = "https://example.com"

response = requests.get(url)

print(response.text)

解释:

  • requests.get():访问网页
  • response.text:网页 HTML 内容

五、第二步:解析网页

网页是 HTML 结构,需要解析。

使用 Beautiful Soup

from bs4 import BeautifulSoup
import requests

url = "https://example.com"
response = requests.get(url)

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

print(soup.title)

输出:

<title>Example Domain</title>


六、第三步:提取数据

例如提取网页标题:

title = soup.title.text
print(title)

提取所有链接:

links = soup.find_all("a")

for link in links:
    print(link.get("href"))


七、完整爬虫示例

一个完整简单爬虫:

import requests
from bs4 import BeautifulSoup

url = "https://example.com"

response = requests.get(url)

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

print("网页标题:", soup.title.text)

links = soup.find_all("a")

for link in links:
    print(link.get("href"))

运行后可以获取:

  • 网页标题
  • 所有链接

八、常见爬虫技巧

1 添加请求头(防止被拒)

headers = {
    "User-Agent":"Mozilla/5.0"
}

requests.get(url, headers=headers)


2 保存数据

保存到文件:

with open("data.txt","w") as f:
    f.write(title)


九、常见爬虫库

Python 爬虫常用工具:

作用
Requests请求网页
Beautiful Soup解析 HTML
Scrapy专业爬虫框架
Selenium模拟浏览器

十、学习爬虫的进阶路线

推荐顺序:

Requests
↓
BeautifulSoup
↓
XPath解析
↓
Scrapy框架
↓
Selenium动态爬虫


十一、爬虫注意事项

  1. 遵守网站 robots.txt
  2. 不要频繁请求
  3. 尊重网站版权
  4. 合法使用数据

✅ 一句话理解爬虫

Python爬虫 = 请求网页 + 解析HTML + 提取数据


如果你愿意,我可以再给你一份 “Python爬虫入门到高手完整路线(10个实战项目)”,包括:

  • 爬取豆瓣电影
  • 爬取新闻网站
  • 爬取电商商品
  • 爬取图片

这些是很多人学习爬虫时做的经典练习。

文章已创建 5130

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部