如何用python爬取小说内容
使用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⑻'
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⑻'
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结构进行相应的调剂。另外,爬取网站内容时需要遵照相关法律法规和网站的爬虫规则,避免对目标网站造成过大的访问压力。
TOP