TypechoJoeTheme

Dcr163的博客

统计

利用Python3抓取百度新医疗专题的图片

2019-08-18
/
0 评论
/
1,262 阅读
/
正在检测是否收录...
08/18

利用python抓取新医疗专题内的图片,废话不多说,直接上代码

#!/usr/bin/python3
#-*- conding:utf-8 -*-
# Create by Dcr163
import requests,re,os,html as Htmls,time,zipfile
#目录下的文件打包zip
def dirZip(src_dir,output_filename):
    # 创建zip文件,用写入的方式
    myzip = zipfile.ZipFile(output_filename,'w')
    # 读取源目录上级目录的字符长度
    dirnameLen = len( os.path.dirname(src_dir) )
    # 遍历源目录下的所有文件及文件夹
    for parent, dirnames, filenames in os.walk(src_dir):
        for file in filenames:
            # 拼接真实的文件地址
            pathfile = os.path.join(parent, file)
            # 相对路径
            arcname = pathfile[dirnameLen:].strip(os.path.sep)
            # 添加到zip中保存为
            myzip.write(pathfile, arcname)
    #关闭zip
    myzip.close()
    print(output_filename,'打包完毕')

# 下载百度专题图片
def downUrlImg(url,saveDir=''):
    #获取网页内容
    r = requests.get(url)
    html = (r.text)
    #获取iframe内的真实链接 正则
    iframeReg = re.compile(r'<iframe src="(http[s]?://.+)"></iframe>')
    trueUrl = iframeReg.findall(html)

    if trueUrl == []:
        print('未拿到正确的专题地址')
        return
    #真实地址
    r = requests.get( Htmls.unescape(trueUrl[0]) )  #Htmls.unescape(trueUrl[0]) 把网页的特殊符号转换为正常符号
    r.encoding = r.apparent_encoding
    html = (r.text)



    #正则匹配图片地址
    # https://imagelib.cdn.bcebos.com/cip_ml_pic7c0f3e7f-209d-4ce3-931e-ab9549d4e3d3.png
    reg = re.compile(r'http[s]?://[\w\.\-]+/[\w_\-]*\.\b[jpg|jpeg|png|gif|mp4]+\b')
    lists1 = reg.findall(html)



    # 正则匹配图片地址 (20200812更新)
    # https://jmy-pic.wejianzhan.com/0/pic/a18d0e807647bd6ec6f09b079d505cf9.jpg
    reg = re.compile(r'http[s]?://[\w\.\-]+/\d+/\w+/[\w\_\d]+\.\b[jpg|jpeg|png|gif|mp4]+\b')
    lists2 = reg.findall(html)

    # https://lemonpro.cdn.bcebos.com/image/15968532819603679170a0ae4417-d4c2-4c3c-ae40-63a7fba8c93b.jpg 案例+商品图片
    # https://lemonpro.cdn.bcebos.com/image/1577337762446-67393-3f379809-4446-495e-8eb7-39c58e3cefe4.jpg@!scale525_525 @!scale\d+_\d+
    reg = re.compile(r'http[s]?://[\w\.\-]+[/]+[\w]+/[\w_\-]*\.\b[jpg|jpeg|png|gif|mp4]+\b')
    lists3 = reg.findall(html)
    # 重新组合新的图片规则
    newList3 = []
    if lists3:
        for img in lists3:
            newList3.append(img+'@!scale525_525')
        lists3 = newList3
        pass

    # 合并数据
    lists = lists1+lists2+lists3
    if len(lists) <= 0:
        exit('没有匹配到任何图片')
    #今天日期格式化
    nowTime = time.strftime('%Y%m%d',time.localtime())
    # 文件保存路径
    filePath = 'D:\python\\baiduWap\{nowDay}\{dir}'.format(nowDay=nowTime, dir=saveDir)
    # 判断目录是否存在,不存在则创建
    if os.path.isdir(filePath) == False:
        os.makedirs(filePath)
    if( lists ):
        i = 0
        print('总共: {total} 张图片'.format(total=len(lists)))
        for img in lists:
            i += 1
            #文件后缀根据后缀自动截取类似 .png|.jpg|.gif
            fileSuffix = img[img.rfind('.'):len(img)]
            #把 @!scale525_525 后缀去掉 20201207更新
            fileSuffix = fileSuffix.replace('@!scale525_525','')
            #文件名称
            fileTruePath = filePath + ('\{name}{suffix}'.format(name=i,suffix=fileSuffix))
            print('正在下载第:{number}张图片'.format(number=i))
            imgContent = requests.get(img).content
            with open(fileTruePath,'ab+') as f:
                f.write(imgContent)
    print('下载完成')
    #打包文件夹
    dirZip(filePath,filePath+'.zip')

#下载百度咨询页面的banner图片
def adaDown(url,saveDir='',baiduid=''):
    # 获取网页内容
    headers = {'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36'}
    # 百度咨询页需要BAIDUID这个cookie
    cookies = dict(BAIDUID=baiduid)
    r = requests.get(url,headers=headers,cookies=cookies)
    html = (r.text)
    reg400 = re.compile(r'错误码:400')
    in400 = reg400.findall(html)
    if len(in400) > 0:
        # 因为没有baiduid所以导致访问失败,所以再次调用即可下载图片
        baiduId = r.cookies['BAIDUID']
        print('初始页面,已获取 BAIDUID:{baiduid} '.format(baiduid=baiduId))
        adaDown(url,saveDir,baiduId)
        return
    reg = re.compile(r'https://imagelib\.cdn\.bcebos\.com/[^"]+\.\b[jpeg|png|gif|mp4]+_[\w\d]+\.\b[jpeg|png|gif|mp4]+\b')
    lists = reg.findall(html)
    # 今天日期格式化
    nowTime = time.strftime('%Y%m%d', time.localtime())
    # 文件保存路径
    filePath = 'D:\python\\baiduWap\{nowDay}\{dir}'.format(nowDay=nowTime, dir=saveDir)
    # 判断目录是否存在,不存在则创建
    if os.path.isdir(filePath) == False:
        os.makedirs(filePath)
    if (lists):
        i = 0
        print('总共: {total} 张图片'.format(total=len(lists)))
        for img in lists:
            i += 1
            # 文件后缀根据后缀自动截取类似 .png|.jpg|.gif
            fileSuffix = img[img.rfind('.'):len(img)]
            # 文件名称
            fileTruePath = filePath + ('\{name}{suffix}'.format(name=i, suffix=fileSuffix))
            print('正在下载第:{number}张图片'.format(number=i))
            imgContent = requests.get(img).content
            with open(fileTruePath, 'ab+') as f:
                f.write(imgContent)
    print('下载完成')
    # 打包文件夹
    dirZip(filePath, filePath + '.zip')
#
if __name__ == '__main__':

    # 百度专题列表 用字典的方式排序,前面是链接,后面是保存的文件夹名称; ym.wejianzhan.com 开头的看起来是正常的页面   ada.baidu.com 是咨询页面
    urlList = {
        'https://ym.wejianzhan.com/site/tjbolaimei.cn/809154e0-c7cf-4535-9798-00dbbc3b8c38':'胸部整形',
    }
    print( '===开始下载,总共 {number} 个专题==='.format(number=len(urlList)) )
    i=0
    for key in urlList:
        i += 1
        print('---正在下载第 {number} 个链接图片---'.format(number=i))
        # 咨询页面
        if 'ada.baidu.com' in key:
            adaDown(key,urlList[key])
        # 专题页面
        else:
            downUrlImg(key, urlList[key])
    print('所有链接图片下载完毕!')

结果如下图所示:

朗读
赞(0)
版权属于:

Dcr163的博客

本文链接:

http://dcr163.cn/216.html(转载时请注明本文出处及文章链接)

评论 (0)

人生倒计时

今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月

最新回复

  1. slot mpo terbaru
    2025-02-08
  2. Sherry Stockdill
    2025-01-28
  3. slot demo
    2025-01-13
  4. 陌天
    2025-01-09
  5. Kerrie Bostick
    2024-12-28

标签云