爬虫初体验_爬取少量百度图片

爬虫初体验_爬取少量百度图片


前言

刚刚开始学习爬虫,爬点图片练练手


一、处理url

打开百度图片网址
任意输入关键字进行搜索
此处以 kobe 为例
在这里插入图片描述其中url栏的内容为:

https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&fm=index&pos=history&word=kobe

不过为了方便讲解(其实是因为其他的参数我不太懂,希望各位赐教 ),此处的url可以简化成以下形式:

https://image.baidu.com/search/index?tn=baiduimage&word=kobe

二、开搞

1.导入requests库

如果没有安装可以通过 pip install requests 来安装

import requests

2.爬取网页的源代码

import requests

url = "https://image.baidu.com/search/index?tn=baiduimage&word=kobe"
# 通过往headers里面添加UA和cookie来绕过小小的反爬
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36",
    "Cookie": "xxxxxxxx"  # 通过浏览器F12查看
}
resp = requests.get(url=url, headers=headers)
resp.encoding = 'utf-8'
with open("kobe.html", mode="w", encoding="utf-8") as f:
    f.write(resp.text)
f.close()
print("over!!!")

这里可能会有小伙伴问:在浏览器鼠标右键不就能看吗?为什么还要爬下来?

因为我发现百度图片的数据是在客户端渲染,右键查看的源代码中是没有数据的
(个人观点,如果错了希望大佬可以提醒我)

在这里插入图片描述
在爬下来的源代码中可以发现图片的url链接

3.处理源代码

导入re模块

import requests
import re

url = "https://image.baidu.com/search/index?tn=baiduimage&word=kobe"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36",
    "Cookie": "xxxxxxxx"
}
resp = requests.get(url=url, headers=headers)
resp.encoding = 'utf-8'
# 这里直接对源代码进行正则匹配
# with open("kobe.html", mode="w", encoding="utf-8") as f:
#     f.write(resp.text)
# f.close()
obj = re.compile(r'"objURL":"(?P<img_url>.*?)"', re.S)
result = obj.finditer(resp.text)  # 获得页面中所有图片的链接
n = 1  # 用来命名下载的图片
for i in result:
    img_url = i.group("img_url")
    img = requests.get(url=img_url)
    name = 'kobe_' + str(n) + '.jpg'
    with open("img/kobe/"+name, mode="wb") as f:
        f.write(img.content)
    f.close()
    n += 1
print("over!!!")

三、成功获得图片

在这里插入图片描述


总结

因为百度图片好像采用了ajax异步请求,到达知识盲区了,不过在我学到后也会更新的,如果文章中有错误希望大家可以指正一下,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值