网络爬虫本质上就是用程序模拟浏览器访问网页,然后把页面中我们需要的内容提取出来。对于初学者来说,不必一开始就追求复杂框架,可以先掌握 发送请求、解析页面、保存数据 这三个核心步骤。
下面以抓取一个包含标题列表的网页为例,演示如何编写一个简单的 Python 爬虫。
需要先安装两个常用库:
pip install requests beautifulsoup4其中:
requests 用于发送网络请求;BeautifulSoup 用于解析 HTML 页面内容。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 中,可以这样写:
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))robots.txt 和使用条款。Selenium、Playwright 或分析接口请求。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。