python爬虫零基础入门(一)三行代码下载图片

爬取访问网站的小问题,代码如下

import urllib.request
response=urllib.request.urlopen("https://www.pexels.com/search/book")cat_img=response.read()

出现下列错误

有些网站为了防止这种非正常的访问,会验证请求信息中的UserAgent(它的信息包括硬件平台、系统软件、应用软件和用户个人偏好),如果UserAgent存在异常或者是不存在,那么这次请求将会被拒绝(如上错误信息所示)

那么我们应该怎么办呢?简单,以大家现在的水平,找软的柿子捏,下面有个网站没有防御系统

import urllib.request
response=urllib.request.urlopen("http://placekitten.com/g/200/300")cat_img=response.read()with open('cat_200_300.jpg','wb') as f:    f.write(cat_img)


这样,你就能在你的路径里面发现下载的图片

对付有防御能力的网站,只能另想办法,我们可以利用下面的代码访问有防御能力的网站,仔细看看两个代码的不同之处。

import urllib.request
req = urllib.request.Request("https://www.pexels.com/search/book")req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36')response=urllib.request.urlopen(req)wy = response.read()

下面做一个小练习,爬取下载刘亦菲女神的图片,这个网站是百度上的刘亦菲图片。

import urllib.request
response=urllib.request.urlopen("https://pic.sogou.com/d?query=%C1%F5%D2%E0%B7%C6&mode=1&did=2#did1")
girl_img=response.read()
with open('cat_200_300.jpg','wb') as f:
    f.write(girl_img)

参考来源:https://blog.csdn.net/The_Time_Runner/article/details/86522700

《零基础入门学习python》

图片与资源来源网站:

1 https://pixabay.com/zh/

2 https://www.pexels.com

3 https://picjumbo.com

4 https://fancycrave.com

5 https://www.foodiesfeed.com

6 https://www.pakutaso.com

7 https://isorepublic.com

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值