温馨提示×

怎么用python爬取小说内容

小亿
109
2023-09-12 09:11:03
栏目: 编程语言

使用Python爬取小说内容,可以使用requests库发送HTTP请求获取小说网站的HTML内容,然后使用BeautifulSoup库解析HTML,并提取出小说的章节链接。再次使用requests库发送HTTP请求获取每个章节的HTML内容,最后使用正则表达式或者BeautifulSoup库提取出章节的具体内容。

下面是一个简单的示例代码:

```python
import requests
from bs4 import BeautifulSoup
import re

def get_novel_content(url):
   # 发送HTTP请求获取网页内容
   response = requests.get(url)
   response.encoding = 'utf-8'
   html = response.text
   
   # 使用BeautifulSoup解析HTML
   soup = BeautifulSoup(html, 'html.parser')
   
   # 提取小说章节链接
   chapter_links = soup.find_all('a', href=re.compile("chapter"))
   
   # 逐个章节爬取内容
   for link in chapter_links:
       chapter_url = url + link['href']  # 拼接完整的章节链接
       
       # 发送HTTP请求获取章节内容
       chapter_response = requests.get(chapter_url)
       chapter_response.encoding = 'utf-8'
       chapter_html = chapter_response.text
       
       # 使用正则表达式提取章节标题和内容
       chapter_title = re.search('

(.*?)

', chapter_html).group(1)
       chapter_content = re.search('

(.*?)

', chapter_html, re.S).group(1)
       
       # 打印章节标题和内容
       print(chapter_title)
       print(chapter_content)
       print('------------------------------')

# 示例:爬取《斗破苍穹》小说
novel_url = 'http://www.xxxx.com/'  # 小说网站的URL
get_novel_content(novel_url)
```

需要注意的是,具体爬取小说内容的代码会因不同的小说网站而有所不同,需要根据目标网站的HTML结构进行相应的调整。另外,爬取网站内容时需要遵守相关法律法规和网站的爬虫规则,避免对目标网站造成过大的访问压力。

0