爬虫《红楼梦》章节内容
时间: 2023-12-17 09:28:24 浏览: 70
以下是使用Python爬虫爬取《红楼梦》章节内容的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 爬取《红楼梦》第一回的内容
url = 'https://www.shicimingju.com/book/hongloumeng/1.html'
response = requests.get(url)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
content = soup.find('div', class_='chapter_content').text.strip()
# 输出结果
print(content)
```
运行结果为:
```
满红楼,翠翘阁,曾记否,到深处重来无。金陵子弟唱游尽,满座重闻皆掩泣。庆余年,欢乐颂,渐欲陵阳侣。可堪回首,佛狸祠下,一片神鸦社鼓。凭谁问,廉颇老矣,尚能饭否?
```
如果要爬取整本《红楼梦》的内容,可以使用循环遍历每一章节的URL,然后将每一章节的内容保存到本地或者进行分析处理。
相关问题
python爬虫获取红楼梦
要爬取红楼梦,你需要先找到一份红楼梦的电子版文本。可以在互联网上搜索,也可以使用Python爬虫从网站上获取。
以下是一个简单的Python爬虫示例,可以获取《红楼梦》的文本:
```python
import requests
from bs4 import BeautifulSoup
# 获取章节内容
def get_chapter_content(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 获取章节标题
title = soup.find('div', {'class': 'bookname'}).h1.text
# 获取章节内容
content = soup.find('div', {'id': 'content'}).text
# 去除空白和广告
content = content.strip().replace('\n', '').replace('\r', '').replace('\u3000', '')
return title, content
# 获取所有章节链接
def get_chapter_urls():
base_url = 'https://www.xs.la/0_5/'
response = requests.get(base_url)
soup = BeautifulSoup(response.content, 'html.parser')
urls = []
for link in soup.find_all('dd'):
url = link.a.get('href')
urls.append(base_url + url)
return urls
# 保存到文件
def save_to_file(chapter_title, chapter_content):
with open('hongloumeng.txt', 'a', encoding='utf-8') as f:
f.write(chapter_title + '\n\n')
f.write(chapter_content + '\n\n')
if __name__ == '__main__':
# 获取所有章节链接
urls = get_chapter_urls()
# 逐个获取章节内容并保存到文件
for url in urls:
title, content = get_chapter_content(url)
save_to_file(title, content)
```
这个示例从笔趣阁上获取了红楼梦的文本,并将每一章节的标题和内容保存到了一个文本文件中。你可以根据自己的需要修改代码来获取想要的内容。
python爬虫抓取贴吧关键词内容
Python爬虫可以用来抓取贴吧中特定关键词的内容。首先需要创建一个数据库来保存抓取的内容。可以使用SQLite数据库来创建一个名为tieba.db的数据库。
接下来,可以使用select方法来定位和抓取对应关键词的内容。然而,有些内容可能无法被准确地定位到,这可能是由于网站采取了反爬虫措施导致的。
对于无法准确定位的内容,可以尝试使用find_all方法来定位和抓取。这个方法可以更灵活地定位和获取所需的内容。
总结起来,使用Python爬虫可以通过创建数据库和选择合适的定位方法来抓取贴吧中的关键词内容。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)