【python零基础爬虫入门】,爬取百度图片,小孩子也能学会

【python零基础爬虫入门】,爬取百度图片,小孩子也能学会

先上效果图
在这里插入图片描述
需要头文件

import re
import requests
import os

因为爬虫需要用到请求网络部分,所以需要这两个包,没有的话自行下载即可。

请求头

 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36'

完整的请求

url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=='+name+'+&pn='+str(i*30)
        result = requests.get(url,headers=headers)
        dowmloadPic(result.content.decode(), name)

得到了html之后需要用到正则表达式

 pic_url = re.findall('"objURL":"(.*?)",',html,re.S)

最后直接把请求到的图片下载好就行

 fp = open(dir, 'wb')
        fp.write(pic.content)
        fp.close()

完整代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
import requests
import os


def dowmloadPic(html, keyword,i):
    pic_url = re.findall('"objURL":"(.*?)",',html,re.S)
   
    abc=i*60
    print('找到关键词:' + keyword + '的图片,现在开始下载图片...')
    for each in pic_url:
        print('正在下载第' + str(abc) + '张图片,图片地址:' + str(each))
        try:
            pic = requests.get(each, timeout=10)
        except requests.exceptions.ConnectionError:
            print('【错误】当前图片无法下载')
            continue

        dir = r'D:\image\i' + keyword + '_' + str(abc) + '.jpg'
        if not os.path.exists('D:\image'):
            os.makedirs('D:\image')
        
        fp = open(dir, 'wb')
        fp.write(pic.content)
        fp.close()
        abc += 1


if __name__ == '__main__':
    #word = input("Input key word: ")
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36'}
    name = input('输入下载图片的名字')
    num = 0
    x = input('您要爬取几张呢?,n*60')

    for i in range(int(x)):
        url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=='+name+'+&pn='+str(i*30)
        result = requests.get(url,headers=headers)
        dowmloadPic(result.content.decode(), name,i)
print("下载完成")

有想学爬虫的小伙伴也可以找我交流一下。

  • 115
    点赞
  • 494
    收藏
    觉得还不错? 一键收藏
  • 28
    评论
Python爬虫是一种可以自动从网页上获取数据的程序。以下是使用Python编写简单的爬虫程序来爬取图片的基本过程: 1. 准备工作:导入所需的库,例如requests和re。设置请求头,以模拟浏览器发送请求。创建一个文件夹来存储下载的图片。 2. 发送请求并获取响应:使用requests库发送GET请求,传入目标网址和请求头。获取响应内容。 3. 解析响应内容:使用正则表达式找到所有图片的URL。正则表达式的模式可以根据具体的网页结构进行调整。 4. 遍历图片URL并下载:使用循环遍历每个图片URL,发送请求并获取响应。将响应内容保存到文件中,命名为图片的标题加上图片的后缀。 下面是一个简单的爬虫程序示例: ```python import requests import re import os image_folder = '表情包' # 设置保存图片的文件夹名称 if not os.path.exists(image_folder): os.mkdir(image_folder) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0' } response = requests.get('https://qq.yh31.com/zjbq/', headers=headers) response.encoding = 'utf-8' t = r'<img src="(.*?)" alt="(.*?)" width="160" height="120">' result = re.findall(t, response.text) for img in result: res = requests.get(img[0]) s = img[0].split('.')[-1] with open(image_folder + '/' + img[1] + '.' + s, mode='wb') as file: file.write(res.content) ``` 请注意,根据不同的网站和页面结构,代码中的正则表达式模式和其他部分可能需要进行适当的调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 28
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值