基于bs4中的一个模块BeautifulSoup进行解析数据的一种方法
爬取诗词名句中三国演义小说
1.导入库
import requestsfrom 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')#解析出章节标题和详情页urlli_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 requestsfrom bs4 import BeautifulSoupurl = '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_enCodingresp = resp.text#实例化一个BeautifulSoup对象soup = BeautifulSoup(resp,'lxml')#解析出章节标题和详情页urlli_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的一个简单用法,后面继续补充。。。
以上是内存溢出为你收集整理的python爬虫简单实战(三)全部内容,希望文章能够帮你解决python爬虫简单实战(三)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)