下面是一篇可直接参考的 Python 爬虫入门文章,附带完整代码示例。示例仅用于学习网页数据抓取,实际使用时请遵守目标网站的 robots.txt、服务条款和相关法律法规,不要高频抓取,也不要抓取个人隐私、付费内容或受版权保护的数据。
网页爬虫的本质可以拆成四步:
先安装两个常用库:
pip install requests beautifulsoup4其中:
requests 用于发送 HTTP 请求;BeautifulSoup 用于解析 HTML。下面这个例子会抓取网页标题和所有链接文本。
import requests
from bs4 import BeautifulSoup
def fetch_page(url: str) -> str:
"""获取网页 HTML 内容"""
headers = {
"User-Agent": "Mozilla/5.0 (compatible; PythonLearningBot/1.0)"
}
response = requests.get(url, headers=headers, timeout=10)
response.encoding = response.apparent_encoding
response.raise_for_status()
return response.text
def parse_page(html: str):
"""解析网页标题和链接"""
soup = BeautifulSoup(html, "html.parser")
title = soup.title.string if soup.title else "未找到标题"
links = []
for a in soup.find_all("a", href=True):
text = a.get_text(strip=True)
href = a["href"]
if text and href:
links.append({"text": text, "href": href})
return title, links
def save_to_txt(title: str, links: list, filename: str = "result.txt"):
"""将结果保存到文本文件"""
with open(filename, "w", encoding="utf-8") as f:
f.write(f"页面标题:{title}\n")
f.write("=" * 40 + "\n")
for i, link in enumerate(links, 1):
f.write(f"{i}. {link['text']} | {link['href']}\n")
def main():
url = "https://wlt.nz826.com/" # 示例练习网站
print(f"正在抓取:{url}")
html = fetch_page(url)
title, links = parse_page(html)
print(f"页面标题:{title}")
print(f"共找到 {len(links)} 个链接")
save_to_txt(title, links)
print("结果已保存到 result.txt")
if __name__ == "__main__":
main()函数 | 作用 |
|---|---|
fetch_page | 发送请求并返回网页 HTML |
parse_page | 解析标题和链接 |
save_to_txt | 把结果写入本地文件 |
main | 组织整个抓取流程 |
运行后,程序会把网页标题和链接保存到 result.txt 中。
实际写爬虫时,建议加上异常处理:
def main():
url = "https://wlt.nz826.com/"
try:
print(f"正在抓取:{url}")
html = fetch_page(url)
title, links = parse_page(html)
print(f"页面标题:{title}")
print(f"共找到 {len(links)} 个链接")
save_to_txt(title, links)
print("结果已保存到 result.txt")
except requests.exceptions.RequestException as e:
print(f"请求失败:{e}")
except Exception as e:
print(f"运行出错:{e}")如果只是学习爬虫,可以按这个顺序继续扩展:
time.sleep 控制请求频率;pandas 做数据整理;写爬虫时最重要的是保持克制:只抓取公开、可合法使用的数据,控制请求频率,避免给目标网站造成压力。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。