python 利用requests和BeautifulSoup爬取网页文章

学习使用request来爬取网页,抓取特定标签元素的内容将其保存到本地。

'''
下载每一篇文章到本地文件,并在本地按照分类标签新建文件夹,将下载的文章按照标签分类放在各自所属文件夹内
'''
import requests
from bs4 import BeautifulSoup
import re
import os

url = 'http://www.rensheng5.com/zx/onduzhe/'
a_list = []
direct={'rensheng':'人生',
      'renwu':'人物',
      'wy':'文苑',
      'shehui':'社会',
      'shenghuo':'生活',
      'wenming':'文明',
      'diandi':'点滴'
      }


def task_init():
    res = requests.get(url)
    res.encoding = res.apparent_encoding
    html = res.text

    soup = BeautifulSoup(html, 'html.parser')
    div  = soup.find('div', {'class':'zzinfo'})
    a_lst = div.findAll('a')
    for a in a_lst:
        if re.match(r'(.*)html$', a['href']):
            a_list.append(a['href'])



#创建所属文件夹,根据href链接获取文章页面所在文件夹名称
def create_file(a_list):
    names=[]
    for a in a_list:
        names.append(a.split('/')[-2])
        #print('names:',names)
    #转换为集合去重
    names=list(set(names))
    print('names:',names)
    #创建文件夹
    try:
        for name in names:
            os.mkdir(direct.get(name))
    except FileExistsError:
        print('文件夹已存在')


#逐一获取网页内容
def article_content(url):
    res=requests.get(url)
    res.encoding=res.apparent_encoding
    html=res.text
    #定位标签
    soup=BeautifulSoup(html,'html.parser')#html解析方式,xml.parser
    div_artview=soup.find('div',{'class':'artview'})
    title=div_artview.h1.string
    div_artinfo=soup.find('div',{'class':'artinfo'})
    artinfo=div_artinfo.get_text().strip()
    #获取点击次数
    src=div_artinfo.script['src']
    res=requests.get(src)
    doc=res.text
    #正则取数字
    num=re.search(r'\d+',doc).group()
    #print('num:',num)
    #把点击次数添加到artinfo中
    artinfo=artinfo[:-1]+num+artinfo[-1]
    div_artbody=soup.find('div',{'class':'artbody'})
    artbody=div_artbody.p.get_text()
    print('artbody:',artbody)
    return num,title,artinfo,artbody



def writeToFile():
    for a in a_list:
        try:
            num,title,artinfo,artbody=article_content(a)
            #创建txt文件,文件名以h1标签内容命名
            #获取文章所属分类
            path=a.split('/')[-2]
            with open(direct[path]+'/'+title+'.txt','w',encoding='utf8') as f:
                #content中内容为列表,并且有空格和标签
                f.write(title+'\n')
                f.write(artinfo+'\n')
                f.write(artbody)
        except Exception as e:
            print(e)


if __name__=='__main__':
    task_init()
    print(a_list)
    create_file(a_list)
    writeToFile()

爬取完之后很神奇的一点就是在点滴文件夹下的文件名和内容变为了其他方式的编码,换成gbk也没解决,有大佬知道的话可以告诉我一下!

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值