当涉及到编写一个爬虫案例时,我们可以选择一个简单的目标,例如从一个网站上爬取
文章标题和链接。下面是一个使用 Python 的 requests 库和 BeautifulSoup 库进行网页爬取的
示例案例。
首先,确保你已经安装了必要的库。你可以使用 pip 来安装它们:
bash
pip install requests beautifulsoup4
接 下 来 , 我 们 可 以 编 写 一 个 简 单 的 爬 虫 来 从 一 个 新 闻 网 站 ( 例 如 :
https://news.example.com,注意这里是一个示例网站,你需要替换为真实的网站)爬取新闻
标题和链接。
python
import requests
from bs4 import BeautifulSoup
# 目标网站的 URL
url = 'https://news.example.com/news'
# 发送 HTTP 请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
# 检查请求是否成功
if response.status_code == 200:
# 使用 BeautifulSoup 解析 HTML 内容
soup = BeautifulSoup(response.text, 'html.parser')
# 假设新闻标题和链接都包含在<a>标签内,并且有一个特定的 class(这里用
'news-title'作为示例)
# 你需要根据实际网页结构进行调整
news_items = soup.find_all('a', class_='news-title')
# 遍历所有新闻条目并打印标题和链接
for news_item in news_items:
title = news_item.get_text(strip=True) # 获取文本并去除前后空格
link = news_item.get('href') # 获取链接(假设 href 属性包含完整的 URL)
print(f'标题: {title}')
print(f'链接: {link}')
print() # 打印一个空行以分隔不同的新闻条目
else:
print(f'请求失败,状态码: {response.status_code}')