网络爬虫(Web Crawler)是一种按照一定规则自动抓取互联网信息的程序。它像是一个不知疲倦的"数据采集员",能够自动访问网页、提取数据并保存下来。Python 因其简洁的语法和丰富的第三方库,成为编写爬虫的首选语言。
在开始之前,确保已安装以下库:
pip install requests beautifulsoup4让我们从最简单的例子开始——抓取一个网页的标题。
import requests
from bs4 import BeautifulSoup
def get_page_title(url):
"""获取网页标题"""
try:
# 发送GET请求
response = requests.get(url, timeout=10)
response.encoding = response.apparent_encoding # 自动识别编码
# 检查请求是否成功
if response.status_code == 200:
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 提取标题
title = soup.title.string
return title
else:
return f"请求失败,状态码:{response.status_code}"
except Exception as e:
return f"发生错误:{str(e)}"
if __name__ == "__main__":
url = "https://wlt.wkhufzl.com"
title = get_page_title(url)
print(f"网页标题:{title}")下面我们来抓取一个简单的新闻列表,提取标题和链接。
import requests
from bs4 import BeautifulSoup
import csv
import time
def fetch_news(url):
"""抓取新闻标题和链接"""
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'
}
try:
response = requests.get(url, headers=headers, timeout=10)
response.encoding = response.apparent_encoding
if response.status_code != 200:
print(f"请求失败,状态码:{response.status_code}")
return []
soup = BeautifulSoup(response.text, 'html.parser')
news_list = []
# 假设新闻标题在 <h2> 标签中,链接在 <a> 标签中
# 实际使用时需要根据目标网站结构调整选择器
articles = soup.find_all('article') or soup.find_all('div', class_='news-item')
for article in articles:
title_tag = article.find('h2') or article.find('a')
if title_tag:
title = title_tag.get_text(strip=True)
link = title_tag.get('href', '')
if link and not link.startswith('http'):
# 拼接完整URL
from urllib.parse import urljoin
link = urljoin(url, link)
news_list.append({'title': title, 'link': link})
return news_list
except Exception as e:
print(f"发生错误:{str(e)}")
return []
def save_to_csv(data, filename='news.csv'):
"""将数据保存为CSV文件"""
if not data:
print("没有数据可保存")
return
with open(filename, 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.DictWriter(f, fieldnames=['title', 'link'])
writer.writeheader()
writer.writerows(data)
print(f"已保存 {len(data)} 条数据到 {filename}")
if __name__ == "__main__":
target_url = "https://wlt.wkhufzl.com" # 示例网站
print(f"正在抓取:{target_url}")
news = fetch_news(target_url)
if news:
for i, item in enumerate(news[:10], 1): # 只打印前10条
print(f"{i}. {item['title']}")
print(f" 链接:{item['link']}\n")
# 保存到文件
save_to_csv(news)
else:
print("未获取到数据")很多网站会检查 User-Agent,如果不设置可能会被拒绝访问。
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...',
'Accept-Language': 'zh-CN,zh;q=0.9',
}import time
time.sleep(2) # 每次请求间隔2秒网络请求随时可能失败,务必使用 try-except 捕获异常。
在爬取任何网站前,先查看 https://域名/robots.txt,了解哪些页面允许爬取。
⚠️ 编写和使用爬虫时请务必注意:
robots.txt 协议本文介绍了 Python 爬虫的基础知识,从最简单的获取网页标题,到抓取新闻列表并保存为 CSV 文件。掌握了 requests 和 BeautifulSoup 这两个库,你已经可以应对大多数静态网页的抓取任务。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。