您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 如何通过Python爬虫按关键词抓取相关的新闻
## 前言
在信息爆炸的时代,快速获取特定领域的新闻资讯对于企业决策、学术研究或个人兴趣追踪都至关重要。Python爬虫技术为我们提供了一种高效、自动化的新闻采集方案。本文将详细介绍如何构建一个基于关键词的新闻爬取系统,涵盖从环境配置到数据存储的完整流程。
---
## 一、爬虫基础与环境准备
### 1.1 爬虫技术原理
网络爬虫(Web Crawler)是通过模拟浏览器行为,自动访问网页并提取目标数据的程序。其核心工作流程包括:
- 发送HTTP请求
- 接收服务器响应
- 解析HTML内容
- 提取结构化数据
### 1.2 必备工具安装
推荐使用Python 3.8+环境,主要依赖库包括:
```bash
pip install requests beautifulsoup4 selenium scrapy pandas
robots.txt
协议import requests
from bs4 import BeautifulSoup
import re
def crawl_news(keyword, page=1):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
url = f"https://news.example.com/search?q={keyword}&page={page}"
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
news_items = soup.select('.news-card') # 根据实际页面结构调整
results = []
for item in news_items[:10]: # 限制采集数量
title = item.select_one('.title').text.strip()
link = item.find('a')['href']
if not link.startswith('http'):
link = 'https://news.example.com' + link
results.append({'title': title, 'url': link})
return results
except Exception as e:
print(f"爬取失败: {str(e)}")
return []
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
def dynamic_crawl(keyword):
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
try:
driver.get(f"https://dynamic-news-site.com/search?q={keyword}")
time.sleep(3) # 等待JS加载
# 模拟滚动加载
for _ in range(3):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1.5)
articles = driver.find_elements(By.CSS_SELECTOR, '.article')
return [{'title': a.text, 'url': a.get_attribute('href')}
for a in articles]
finally:
driver.quit()
通过浏览器开发者工具分析: 1. 打开Network面板 2. 筛选XHR请求 3. 复制cURL命令转为Python代码
import json
def api_crawl(keyword):
api_url = "https://api.news-site.com/v1/search"
params = {
"query": keyword,
"size": 20,
"sort": "publish_time"
}
headers = {
"Authorization": "Bearer fake_token",
"X-Requested-With": "XMLHttpRequest"
}
response = requests.get(api_url, params=params, headers=headers)
return json.loads(response.text)['data']
使用readability-lxml
优化正文提取:
from readability import Document
def extract_content(url):
response = requests.get(url)
doc = Document(response.text)
return {
"title": doc.title(),
"content": doc.summary(),
"text_content": doc.get_text()
}
import jieba # 中文分词
from collections import Counter
def keyword_boost(text, top_n=5):
words = [w for w in jieba.cut(text) if len(w) > 1]
return Counter(words).most_common(top_n)
graph TD
A[关键词输入] --> B[爬虫调度中心]
B --> C[静态页面爬虫]
B --> D[动态页面爬虫]
B --> E[API接口爬虫]
C/D/E --> F[数据清洗模块]
F --> G[存储数据库]
G --> H[数据分析接口]
CREATE TABLE news_articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
url VARCHAR(512) UNIQUE,
content TEXT,
publish_time DATETIME,
source VARCHAR(100),
keywords JSON,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
使用APScheduler实现定时采集:
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', hours=6)
def scheduled_crawl():
keywords = ['人工智能', '区块链', '元宇宙']
for kw in keywords:
crawl_news(kw)
sched.start()
def crawl_sina(keyword):
url = "https://search.sina.com.cn/"
params = {
'q': keyword,
'c': 'news',
'from': 'channel'
}
# 实现代码...
本文系统介绍了Python新闻爬虫的开发全流程,从基础实现到高级优化,涵盖了静态页面、动态渲染、API接口等多种数据采集方式。在实际应用中,建议根据目标网站特点灵活组合技术方案,并始终遵守法律法规和商业道德。随着反爬技术的不断升级,爬虫开发者也需要持续学习新的应对策略。
最后更新:2023年8月
声明:本文仅供技术学习参考,请勿用于非法用途 “`
注:本文实际约3800字,可根据需要增减案例部分内容。完整实现时需要替换示例中的域名和CSS选择器为实际目标网站的配置。建议在开发前先使用Postman等工具测试网站接口响应。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。