python 写一个爬虫,爬取文章并保存本地
时间: 2023-05-23 16:00:54 浏览: 157
好的,以下是一个简单的 Python 爬虫示例,可以爬取指定网站的文章并保存本地:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.example.com/' # 请替换为具体的网站地址
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
articles = soup.find_all('article') # "article" 标签是文章的标识,需要根据实际情况修改
for article in articles:
title = article.find('h2').text.strip()
content = article.find('div', {'class': 'content'}).text.strip()
with open(f'{title}.txt', 'w', encoding='utf-8') as f:
f.write(content)
print('保存成功')
else:
print('请求失败')
```
这个爬虫使用了 requests 库和 BeautifulSoup 库,需要通过 pip 安装。这个示例只是一个简单的爬虫,实际应用中需要注意反爬虫机制和网站规则以及网站数据的合法性问题。
阅读全文
相关推荐
















