python爬虫简单实战(三)

基于bs4中的一个模块BeautifulSoup进行解析数据的一种方法
爬取诗词名句中三国演义小说
1.导入库

import requests
from bs4 import BeautifulSoup

2.发起请求

url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63'
    }
resp = requests.get(url=url,headers=headers)

3.BeautifulSoup进行解析数据

#实例化一个BeautifulSoup对象
soup = BeautifulSoup(resp,'lxml')
#解析出章节标题和详情页url
li_list = soup.select('.book-mulu > ul > li')
for li in li_list:
    title = li.a.string
    detail_url ='https://www.shicimingju.com/' + li.a['href']
    detail_text = requests.get(url=detail_url,headers=headers)
	soup_detail = BeautifulSoup(detail_text,'lxml')
    content = soup_detail.find('div',class_='chapter_content').text

4.结果发现有数据乱码 进行处理后,代码如下:

import requests
from bs4 import BeautifulSoup
url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63'
    }
resp = requests.get(url=url,headers=headers)
#处理乱码数据
resp.encoding = 'utf-8'
resp.apparent_encoding
resp = resp.text
#实例化一个BeautifulSoup对象
soup = BeautifulSoup(resp,'lxml')
#解析出章节标题和详情页url
li_list = soup.select('.book-mulu > ul > li')
for li in li_list:
    title = li.a.string
    detail_url ='https://www.shicimingju.com/' + li.a['href']
    detail_text = requests.get(url=detail_url,headers=headers)
    detail_text.encoding = 'utf-8'
    detail_text.apparent_encoding  # 处理乱码
    detail_text = detail_text.text
    soup_detail = BeautifulSoup(detail_text,'lxml')
    content = soup_detail.find('div',class_='chapter_content').text
    print(title,content,'\n')

5.总结
BeautifulSoup的一个简单用法,后面继续补充。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值