python抓取网络图片保存到本地,通过url抓取文章的标题,通过链接地址,抓取内容数据

版本 : python 3.0
框架 : flask
网页解析库 : PyQuery
数据库 mongodb

抓取百度新闻 关键字为公安

  1. 通过flask,构建服务器,托管从网上下载的图片。
  2. 通过定时任务,每60秒抓取最新新闻数据。
  3. 初始抓起第一页。
  4. 通过对比标题(也可选择时间),如在数据库的第一条数据中和抓取的文章,不一样,就将数据插入到数据库的第一条中

抓取百度新闻标题

''' 
     爬取百度新闻
     :keyword 公安
     :type 1 
     :return 
'''

def baiduReplite(reptiles, time):
    imgArr = []
    baiduWord = "公安部"
    baiduUrl = "https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=" + parse.quote(baiduWord)
    try:
        html = requests.get(url=baiduUrl, headers=headers)
        print("------------------------请求百度新闻成功-----------------------------")
    except BaseException as f:
        print("%s 连接百度新闻超时" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), f)
        return

    html = html.text
    doc = pq(html)

    items = doc("#content_left").items()
    findDom = item.find(".result")
    
    for item in items:
        if reptiles.count({"type": 1}) == 0:  //在数据库中存储是否有初始数据,如没有,就进行抓取第一页的数据,否则就赚取
            for i in range(9, -1, -1):
               title = findDom.eq(i).find('.c-title').text()
               findDom.eq(i).find(".c-summary").find("p").remove()
               findDom.eq(i).find(".c-summary").find("span").remove()
                synopsis = findDom.eq(i).find(".c-summary").text()
                originAddress = findDom.eq(i).find(".c-title").children("a").attr("href")
                imgUrl = findDom.eq(i).find(".c_photo").children("img").attr("src")
                imgArr.append({
                    "title": title,
                    "synopsis": synopsis,
                    "originAddress": originAddress,
                    "imgUrl": imgUrl,
                    "type": 1
                })
        else:
            title =findDom .eq(0).find('.c-title').text()
            findDom.eq(0).find(".c-summary").find("p").remove()
            findDom.eq(0).find(".c-summary").find("span").remove()
            synopsis = findDom.eq(0).find(".c-summary").text()
            originAddress = findDom.eq(0).find(".c-title").children("a").attr("href")
            imgUrl = findDom.eq(0).find(".c_photo").children("img").attr("src")
            if reptiles.find_one({"title": title, "type": 1}) == None:
                imgArr.append({
                    "title": title,
                    "synopsis": synopsis,
                    "originAddress": originAddress,
                    "imgUrl": imgUrl,
                    "type": 1
                })

        for i, data in enumerate(imgArr):
            newImgUrl = request_download(data['imgUrl'], i)
            originAddress = data['originAddress']
            reptiles.insert_one({
                "title": data['title'],
                "synopsis": data['synopsis'],
                "originAddress": originAddress,
                "time": time.strftime("%Y-%m-%d", time.localtime()),
                "imgUrl": newImgUrl,
                "type": 1
            })

爬取文章详情页

'''
  爬取文章详情页
  :articleImgArr 图片数组
'''
def newAddress(httpUrl):
    articleImgArr = []
    html = requests.get(url=httpUrl, headers=headers).text
    doc = pq(html)

    if httpUrl.find("http://www.xxx.com") != -1:
        items = doc(".article").items()
        for item in items:
            html = item.find(".content").html()
            articleImgLength = len(item.find(".content").find("img"))
            for i in range(0, articleImgLength):
                 newI= request_download("http://www.xxx.com" + item.find("img").eq(i).attr("src"), i)
                 articleImgArr.append(newI)
                 html = html.replace(item.find("img").eq(i).attr("src"), articleImgArr[i])
            time = item.find(".title").children("span").text()
            return html, time, newI
    else:
        pass

下载图片

def request_download(imgUrl, i):
    #如果图片不存在,直接返回None,否则进行下载,并进行上传到文件服务上
    if imgUrl == None:
        return No

    try:
        path = './images/'
        folder = os.path.exists(path)
        try:
           pic = requests.get(imgUrl, timeout=1)
        except BaseException as f:
            print("请求图片地址失败", f)
            return
        if not folder:
            os.makedirs(path)
        # timeout 超时时间
        string = path + str(i + 1) + '.jpg'
        with open(string, 'wb') as f:
            f.write(pic.content)
            print('----------------------成功下载第%s张图片: %s------------------------------' % (str(i + 1), str(imgUrl)))
 

    except Exception as e:
        print('下载第%s张图片时失败: %s' % (str(i + 1), str(imgUrl)))

猜你喜欢

转载自blog.csdn.net/qq_32341603/article/details/88652359