用python写一个爬取小说的程序
时间: 2023-05-19 20:01:03 浏览: 72
可以使用Python的requests和BeautifulSoup库来实现爬取小说的程序。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com/novel'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
novel_title = soup.find('h1').text
novel_content = soup.find('div', {'class': 'content'}).text
with open(f'{novel_title}.txt', 'w', encoding='utf-8') as f:
f.write(novel_content)
```
这个程序会爬取指定小说网站的内容,并将小说标题和内容保存到一个文本文件中。你可以根据需要修改代码来适应不同的小说网站。
相关问题
帮我用 Python写一个爬取网站小说的爬虫程序
以下是一个简单的Python爬虫程序,用于爬取小说网站上的小说。
```
import requests
from bs4 import BeautifulSoup
# 设置需要爬取的小说网站URL
url = 'https://www.example.com/novel'
# 发送请求并获取响应
response = requests.get(url)
# 解析HTML响应内容
soup = BeautifulSoup(response.text, 'html.parser')
# 找到小说内容所在的标签
novel_content = soup.find('div', class_='novel-content')
# 打印小说内容
print(novel_content.text)
```
以上代码只是一个简单的示例,实际上爬取网站小说需要考虑到很多方面,比如反爬虫机制、网站结构的变化等等。因此,建议使用更加完善的爬虫框架,如Scrapy等。同时也需要注意法律法规,不得在未经授权的情况下获取版权作品。
帮我用Python写一个爬取网络小说代码,要求爬取到的小说以小说名字加.TXT保存
好的,以下是一个简单的爬取网络小说的Python代码:
```python
import requests
from bs4 import BeautifulSoup
# 输入小说目录页的URL
url = input("请输入小说目录页的URL:")
# 发送请求并获取响应
response = requests.get(url)
response.encoding = response.apparent_encoding
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取小说标题
title = soup.title.string
print(f"正在下载《{title}》......")
# 创建TXT文件,并写入小说章节内容
with open(f"{title}.txt", "w", encoding="utf-8") as f:
# 获取小说章节列表
chapters = soup.find_all('a', href=True)
for chapter in chapters:
chapter_url = chapter['href']
# 发送请求并获取章节内容
chapter_response = requests.get(chapter_url)
chapter_response.encoding = chapter_response.apparent_encoding
chapter_soup = BeautifulSoup(chapter_response.text, 'html.parser')
chapter_title = chapter_soup.title.string
chapter_content = chapter_soup.find('div', class_='content').text
# 写入章节内容
f.write(f"\n\n{chapter_title}\n\n")
f.write(chapter_content)
print(f"{chapter_title} 下载完成")
print("全部下载完成!")
```
使用时,将上述代码保存到一个Python文件中,然后在命令行中运行该文件即可。运行后会要求输入小说目录页的URL,输入后程序会自动下载小说并保存为TXT文件,文件名为小说标题。