教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 如何用python爬虫在知乎上提取图片?

如何用python爬虫在知乎上提取图片?

发布时间:2020-11-29   编辑:jiaochengji.com
教程集为您提供如何用python爬虫在知乎上提取图片?等资源,欢迎您收藏本站,我们将为您提供最新的如何用python爬虫在知乎上提取图片?资源

在下载需要用的软件时,总是会打包出一堆我们不想要的东西,虽然可以点击取消但是稍微不注意就给一起下载出来了,重新把不要的卸载还很麻烦。同样的,我们在知乎上提取想要的数据时,有时候只需要获得图片就足够了。那么有没有什么方法可以用python爬虫在知乎上只提取图片呢?


下面的代码注释请仔细阅读,中间有一个小BUG,需要手动把pic3修改为pic2这个地方目前原因不明确,可能是我本地网络的原因,还有请在项目根目录先创建一个 imgs 的文件夹,用来存储图片

def download_img(self,data):
        ## 下载图片
        for item in data["data"]:
            content = item["content"]
            pattern = re.compile('<noscript>(.*?)</noscript>')
            imgs = pattern.findall(content)
            if len(imgs) > 0:
                for img in imgs:
                    match = re.search('<img src="(.*?)"', img)
                    download = match.groups()[0]
                    download = download.replace("pic3", "pic2")  # 小BUG,pic3的下载不到
                    print("正在下载{}".format(download), end="")
                    try:
                        with requests.Session() as s:
                            with s.get(download) as img_down:
                                # 获取文件名称
                                file = download[download.rindex("/")   1:]
                                content = img_down.content
                                with open("imgs/{}".format(file), "wb ") as f:  # 这个地方进行了硬编码
                                    f.write(content)
                                print("图片下载完成", end="\n")
                    except Exception as e:
                        print(e.args)
            else:
                Pass


运行结果为

 

想要获得更多图片的小伙伴,快点试试小编这个方法吧,大家的文件夹资源又要更新一波啦~更多Python学习推荐:JQ教程网Python大全

您可能感兴趣的文章:
python爬虫一般都爬什么信息
python爬虫能干什么
Python 爬虫学习系列教程
python爬虫技术可以干什么
python在实际工作中的应用有哪些
Python2爬虫入门之如何学习爬虫
Python2爬虫入门:爬虫基础知识
《Python2爬虫入门教程指南》(系列教程)
python学会后做什么
python可以抓取数据吗

[关闭]
~ ~