zoukankan      html  css  js  c++  java
  • python爬取百度图片——翻页式网站爬取

    小编大约于这个月月初写的这一份代码,但很不幸,大概20号,再次找百度图片翻页流的时候,发现是瀑布流且回不去了,还好代码里面留了翻页流的网址

    所以,现在来分享给大家。

    语言:python3.6

    库:requests, re, urllib

    除了requests需要pip install之外,其他两个是python自带的模块,直接调用即可。

    代码中的原网址:https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=小姐姐&pn=0

    直接复制网址可以浏览百度图片翻页流的小姐姐的照片的第一页。好了,代码在下面,详情请见注释。

    #!/usr/bin/python3
    # -*- coding:utf-8 -*-
    # Author:water_chen
    
    
    import requests
    import re
    from urllib import request
    
    def get_picture_list(keyword,biggest_pages):
        all_picture_list = []
        for page in range(biggest_pages):
         # 每一页20张图片, 所以翻页的是0 20 40 80 这样变化的 page
    = page * 20 url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word={}&pn={}'.format(keyword, page)      # html = requests.get(url).content.decode('utf-8') picture_list = re.findall('{"thumbURL":"(.*?)",', html)# 用正则匹配,获得图片的url all_picture_list.extend(picture_list)
      all_picture_list = set(all_picture_list)# 因为第二页也有后面两页的图片,所以要去重
      download_picture(all_picture_list)
    # 下载图片
    def download_picture(all_picture_list):
        for i, pic_url in enumerate(all_picture_list):
            print(i)
         # 在代码的路径下,新建一个picture,图片会由urlretrieve函数保存到本地 string
    = 'picture/{}.jpg'.format(str(i + 1)) request.urlretrieve(pic_url, string) # 开始函数 def start():
       # 你想搜索的关键词 keyword
    = '小姐姐'
       # 你想搜索的页数 biggest_pages = 10 get_picture_list(keyword, biggest_pages) if __name__ == '__main__': start()

    大家赶快保存这个翻页流的网址,现在的百度图片是瀑布流,如果要爬,就需要selenium对网页进行滚动,比较麻烦,这个代码能够比较容易的获取。

    如果有用,请大家点个赞,谢谢。

  • 相关阅读:
    “There appears to be trouble with your network connection. Retrying”
    Nignx 处理异常操作流程
    "...do not match previously installed version; ignoring!"
    文档对象模型(DOM)
    Parsing error: Expression expected.
    让人抓狂的缩进冲突(eslint)
    C#中属性PropertyInfo的使用
    C#调用WebService服务(动态调用)
    pdf转word工具
    PASS系统应用技术手册
  • 原文地址:https://www.cnblogs.com/chenyuan404/p/10192758.html
Copyright © 2011-2022 走看看