使用Python抓取网页文本通常涉及以下步骤:发送HTTP请求获取网页内容、解析HTML结构、提取所需文本,并进行后续处理。以下是综合多个权威来源的详细指南:
一、基础工具与库
-
安装必要库
需要安装
requests
和BeautifulSoup
库。可以使用以下命令安装:pip install requests beautifulsoup4
若处理中文文本,建议额外安装
jieba
进行分词处理。 -
发送HTTP请求
使用
requests
库发送GET请求获取网页内容,并检查响应状态:import requests url = 'https://www.example.com' response = requests.get(url) response.raise_for_status() # 检查请求是否成功 html_content = response.text
二、解析HTML内容
-
解析HTML
使用
BeautifulSoup
解析HTML内容:from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'html.parser')
根据网页结构选择合适的选择器,例如表格行
<tr>
、段落<p>
或自定义类名(如.author
)。 -
提取文本
-
整体提取 :使用
get_text()
方法获取纯文本内容:pure_text = soup.get_text() print(pure_text)
-
结构化提取 :遍历特定标签(如
<tr>
中的<td>
):for block in soup.find_all('tr'): if block.find('td'): for info in block.find_all('td'): text = info.text.strip() # 处理文本(如分词、过滤)
-
三、进阶处理(可选)
-
去除无关内容
使用正则表达式或自定义规则去除CSS、JavaScript、注释等非文本内容:
import re # 去除脚本和样式 clean_text = re.sub(r'<!--.*?-->', '', html_content) clean_text = re.sub(r'<script.*?<\/script>', '', clean_text)
-
文本分析
结合自然语言处理工具(如
jieba
)进行分词、统计等操作:import jieba words = jieba.lcut(clean_text) word_count = {} for word in words: word_count[word] = word_count.get(word, 0) + 1 print(word_count)
四、注意事项
-
遵守规范
-
遵守目标网站的
robots.txt
文件规定; -
设置合理的请求间隔,避免对服务器造成过大压力。
-
-
异常处理
添加错误处理机制,如网络异常、超时处理等:
try: response = requests.get(url, timeout=10) response.raise_for_status() except requests.RequestException as e: print(f"请求失败: {e}")
-
数据存储
将提取的文本保存到文件或数据库中,便于后续分析:
with open('output.txt', 'w', encoding='utf-8') as f: f.write(pure_text)
示例完整代码
以下是一个综合示例,从小说网站抓取章节文本并提取关键词:
import requests
from bs4 import BeautifulSoup
import jieba
import re
def fetch_novel(url):
response = requests.get(url, timeout=10)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
# 假设小说内容在<div class="novel-text">标签中
novel_content = soup.find('div', class_='novel-text').text
# 去除无关内容
clean_text = re.sub(r'<!--.*?-->', '', novel_content)
clean_text = re.sub(r'<script.*?<\/script>', '', clean_text)
# 分词与统计
words = jieba.lcut(clean_text)
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
return word_count
if __name__ == "__main__":
url = 'https://example.com/novel'
word_count = fetch_novel(url)
print(word_count)