分享python3爬虫爬取百度上的图片

话不多说,先上代码

import urllib.request
import re

key="风景图片"
keyname=urllib.request.quote(key)
url="http://image.so.com/i?src=360pic_strong&z=1&i=0&cmg=1760c80a08bb4de0be404c0d98032520&q="+keyname
headers=("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
opener=urllib.request.build_opener()
opener.addheaders=[headers]
urllib.request.install_opener(opener)
pat='"_thumb_bak":"(.*?)"'
data=urllib.request.urlopen(url).read().decode('utf-8','ignore')
allurl=re.compile(pat).findall(data)
for i in range(0,len(allurl)):
    try:
        thisurl=allurl[i]
        this=thisurl.replace('\/','/')
        file="D:/C/爬虫学习网络体系/爬虫爬去内容/风景图片/"+str(i)+".jpg"
        urllib.request.urlretrieve(this,filename=file)

    except urllib.request.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)

其中有一个部分一直失败,经过好多次调试才成功

就是thisurl这个部分,用print得到的网址格式是这样:

http:\/\/p0.so.qhimgs1.com\/sdr\/_240_\/t01610a89bbf5ff392c.jpg

当时我也是一脸懵逼
但是后来想想“/"可以替换下就可以了,要说写这个爬虫也就是这点感觉比较坑。
别的都很好。
你也可以尝试用代理服务器去处理,当然这是比较简单的,微量级的爬虫就不需要了
话不多说,就分享到这吧!继续小爬虫的道路!!!

发布了60 篇原创文章 · 获赞 39 · 访问量 3747

猜你喜欢

转载自blog.csdn.net/qq_42992704/article/details/86756021