python爬取三国演义全文
时间: 2023-09-25 19:10:39 浏览: 90
要用Python爬取《三国演义》全文,可以先通过引用提供的链接访问《三国演义》的在线阅读网页。然后,可以使用Python的网络爬虫库,比如Requests和BeautifulSoup,来获取该网页的内容。
首先,使用Requests库发送GET请求,获取网页的HTML内容。可以使用以下代码来实现:
```python
import requests
url = "https://www.shicimingju.com/book/sanguoyanyi.html"
response = requests.get(url)
html_content = response.text
```
接下来,使用BeautifulSoup库解析HTML内容,并提取出章节的标题和对应的章节网址。可以使用以下代码来实现:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, "html.parser")
chapter_list = soup.find_all("div", class_="book-mulu")
for chapter in chapter_list:
chapter_title = chapter.a.text
chapter_url = chapter.a["href"]
print(chapter_title, chapter_url)
```
通过以上代码,就可以获取到《三国演义》每个章节的标题和对应的章节网址了。
接下来,可以根据章节网址,再次发送GET请求,获取章节的内容。可以使用以下代码来实现:
```python
chapter_url = "章节的网址" # 将章节的网址替换为具体的章节网址
chapter_response = requests.get(chapter_url)
chapter_html = chapter_response.text
```
然后,可以继续使用BeautifulSoup库解析章节的HTML内容,提取出章节的文本内容。可以使用以下代码来实现:
```python
chapter_soup = BeautifulSoup(chapter_html, "html.parser")
chapter_content = chapter_soup.find("div", class_="chapter_content").text
print(chapter_content)
```
通过以上代码,就可以获取到《三国演义》每个章节的内容了。
请注意,以上代码仅为示例,具体的网页结构和解析方式可能会因网页的更新和变化而有所不同。需要根据实际情况进行调整和修改。<span class="em">1</span><span class="em">2</span>
#### 引用[.reference_title]
- *1* *2* [python爬虫-bs4案例爬取三国演义全文-小林月](https://blog.csdn.net/qq_53953480/article/details/129915362)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]