美文网首页
7. Beautiful Soup

7. Beautiful Soup

作者: 薛东弗斯 | 来源:发表于2024-02-26 00:04 被阅读0次
image.png image.png
image.png
image.png
image.png
from bs4 import BeautifulSoup
if __name__=="__main__":
    fp = open('./test.html','r',encoding='utf-8')
    soup = BeautifulSoup(fp,'lxml')
    print(soup)
image.png
image.png
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 爬取三国演义所有章节标题和章节内容
import requests
from bs4 import BeautifulSoup

if __name__=="__main__":
    # 对首页的页面数据进行爬取
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/96.0.4664.45 Safari/537.36'
    }
    url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
    page_text = requests.get(url=url,headers=headers).text
    # 在首页中解析出章节的标题和详情页的url
    #1. 实例化BeautifulSoup对象,需要将页面源码数据加载到该对象中
    soup = BeautifulSoup(page_text,'lxml')  # 此处解析的是首页内容
    # 解析章节标题和详情页的url
    li_list = soup.select('.book-mulu > ul > li')
    fp = open('./sanguo.txt','w',encoding='utf-8')
    for li in li_list:
        title = str(li.a.string)
        detail_url = 'https://www.shicimingju.com'+li.a['href']
        # 对详情页发起请求,解析出章节内容
        detail_page_text = requests.get(url=detail_url,headers=headers).text
        # 解析成详情页中相关的章节内容
        detail_soup = BeautifulSoup(detail_page_text,'lxml')
        # print(detail_soup)
        div_tag = detail_soup.find('div',class_='chapter_content')
        #  解析到了章节的内容
        content = div_tag.text
        fp.write(title+':'+ content + '\n')
        print(title + '爬取成功!!!')

相关文章

网友评论

      本文标题:7. Beautiful Soup

      本文链接:https://www.haomeiwen.com/subject/qzroadtx.html