写python代码。爬虫一个网站的小说
时间: 2023-07-07 15:18:19 浏览: 42
以下是一个简单的Python爬虫,用于爬取指定网站上的小说内容:
```python
import requests
from bs4 import BeautifulSoup
# 设置目标小说的url和文件名
novel_url = 'http://www.example.com/novel.html'
filename = 'novel.txt'
# 发起请求并获取html文本
response = requests.get(novel_url)
html = response.text
# 使用BeautifulSoup解析html文本
soup = BeautifulSoup(html, 'html.parser')
# 获取小说正文部分的标签
main_text = soup.find('div', {'id': 'novel-text'})
# 将正文部分的每一段落内容写入文件中
with open(filename, 'w', encoding='utf-8') as f:
for p in main_text.find_all('p'):
f.write(p.text + '\n')
```
在上面的代码中,我们使用了requests库来发起网络请求,使用BeautifulSoup库来解析html文本。首先,我们需要设置目标小说的url和我们要保存到的文件名。然后,我们发起请求并获取html文本。接着,我们使用BeautifulSoup库解析html文本,并找到小说正文部分的标签。最后,我们遍历正文部分的每一段落内容,并将其写入文件中。