Python bs4库 爬取小说

学习目标:

利用bs4库爬取小说(笔趣阁)

学习内容:

bs4库:(from bs4 import BeautifulSoup)
可以将网页源码转化为对象:soup=BeautifulSoup(Html,‘lxml’)
对对象进行解析:利用网页中的标签
soup.a ------soup.a.text/string
soup.find(‘div’)
soup.find_all(‘div’)
soup.select(’.class>a>b’)//层级
soup.select(’.class>a c’)//跨层级
属性:
soup.a[‘href/title’]

学习产出:

import requests
from bs4 import BeautifulSoup
import os

if __name__=='__main__':
    if not os.path.exists('./元尊'):
        os.mkdir('./元尊')
    url='https://www.bqkan8.com/0_790/'
    
    headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
        }

    response=requests.get(url=url,headers=headers)
    page_text=response.text.encode('iso-8859-1')

    soup=BeautifulSoup(page_text,'lxml')

    yzlist=soup.select('.listmain>dl dd')

    for li in yzlist[12:53]:
        title=li.a.string
        fp=open('./元尊/'+title+'.txt','w',encoding='utf-8')
        detail_url='https://www.bqkan8.com'+li.a['href']

        detail_page=requests.get(url=detail_url,headers=headers).text

        detail_soup=BeautifulSoup(detail_page,'lxml')

        div_tag=detail_soup.find('div',class_='showtxt')

        content=div_tag.text
        fp.write(title+':'+'\n'+content+'\n')
        fp.close()
        print(title,'over')

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值