python百度搜索url爬取 图片

这里以百度搜索为案例,搜索并下载图片

import requests # python HTTP客户端库,编写爬虫和测试服务器响应数据会用到的类库
import re # 导入正则表达式模块
import random # 导入模块,随机生成一个实数,取值范围[0,1]
# 从百度下载图片
# 百度图片 改变url  word参数
# https://images.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1517907399736_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=1

# 定义函数
def spiderPic (html, keyword):
    print('正在查找:'+keyword+'  对应的图片,正在从百度下载图片')
    # addr 为爬取的地址
    for addr in re.findall('"objURL":"(.*?)"', html, re.S):
        # 超过36个字符长度,超出部分变为省略号
        print('正在爬取URL地址'+str(addr)[0:35]+"...")
        try:
            # 请求图像的URL地址(最大时间10s)
             pics = requests.get(addr, timeout=10)
        except requests.exception.ConnectionError:
             print("error")
             continue
        # 路径     随机生成数0~1000   4位数    wb:二进制
        fq = open("C:\\Users\\锴\\Desktop\\test\\"+(str(random.randrange(0, 1000, 4))+'.jpg'), 'wb')
        # 写入本地
        fq.write(pics.content)

#主函数
if __name__ == '__main__':
    word = input('请输入爬取图像关键词:')# 输入关键词
    #得到搜索结果
    result = requests.get('https://images.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1517907399736_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word='+word)
#调用函数
spiderPic(result.text, word)


猜你喜欢

转载自blog.csdn.net/super_sloppy/article/details/79273740