美文网首页
Python 简单爬百度图片

Python 简单爬百度图片

作者: 隐身人 | 来源:发表于2018-12-17 14:48 被阅读39次

今天项目需要爬点图片资源,so,接触了一下现在火热的 Python 。

本例子适合 Python 新手 尝试一下 Python 爬 数据体验。

工具:Mac端 Python 3 软件。

下载地址:
Mac 端 下载地址: 点击下载安装程序
Windows 端 下载地址 : 点击下载64位 安装程序 / 点击下载32位 安装程序

代码模块:
1.添加库
2.参数配置
3.下载方法
4.调用方法

go...

添加库

>>> import re 添加 导入正则表达式模块库
>>> import random 添加 随机生成一个数模块库
>>> import requests 添加 python HTTP客户端 编写爬虫和测试服务器经常用到的模块库

参数配置


>>> if  __name__ == '__main__':
    promptText = input('请输入你要搜索的图片关键字:')
    targetUrl = requests.get('http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201812170&lm=-1&cl=2&nc=1&ie=utf-8&word=' + promptText)


下载方法


>>> def downloadMethods(html,keyword):
    print('正在查找 ' + keyword +' 对应的图片   ----   Download......')
    for addr in re.findall('"objURL":"(.*?)"',html,re.S):     
        print('正在爬取URL地址:'+str(addr)[0:30]+'...')  
 
        try:
            pics = requests.get(addr,timeout=10)  
        except requests.exceptions.ConnectionError:
            print('您当前请求的URL地址出现错误')
            continue
 
        fq = open('/Users/mac/Downloads/下载test数据/' + (keyword+'_'+str(random.randrange(0,1000,4))+'.jpg'),'wb')    
        fq.write(pics.content)
        fq.close()

调用方法



>>> downloadMethods(targetUrl.text,promptText)

程序代码运行图

代码运行图

查看爬到的百度图片

爬到的图片

相关文章

网友评论

      本文标题:Python 简单爬百度图片

      本文链接:https://www.haomeiwen.com/subject/feoqkqtx.html