通过bs4爬取三国演义

爬取三国演义:

import requests
from bs4 import BeautifulSoup  # 新的认知 只能解析首页

url = 'https://www.shicimingju.com/book/sanguoyanyi.html'

response = requests.get(url)  # 获取字符串型的数据
f = open('./sanguo.txt','w',encoding='utf-8')

response.encoding = 'utf-8'
response = response.text
# 数据解析
soup = BeautifulSoup(response, 'lxml')
a_list = soup.select('.book-mulu > ul > li > a')
for a in a_list:
    title = a.string
    url1 = 'https://www.shicimingju.com' + a['href']
    # 对详情页发起请求 获取 章节内容
    page_text = requests.get(url1)
    page_text.encoding = 'utf-8'
    page_text = page_text.text
    soup = BeautifulSoup(page_text, 'lxml')
    # a = soup.xpath('//*[@id="main_left"]/div[1]/div')
    divs = soup.find('div',class_ ='chapter_content')
    com = divs.text
    f.write(title+':'+com+'\n')
    print('保存成功!')
print('结束!')
f.close()

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
要用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 ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itLaity

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值