Python实战爬虫:爬图片

python爬虫爬图片

爬虫爬baidu图片

第一步

载入爬虫模块

from requests_html import HTMLSession            #载入爬虫模块

第二步

创建session对象

from requests_html import HTMLSession            #载入爬虫模块
session =HTMLSession() #创建完毕

推荐Python大牛在线分享技术 扣qun:855408893

领域:web开发,爬虫,数据分析,数据挖掘,人工智能

零基础到项目实战,7天学习上手做项目

第三步

获得发现百度图片搜索规律并发起请求并匹配到图片的url

[http://image.baidu.com/search/index?tn=baiduimage&fm=result&ie=utf-8&word=我们搜图片的关键字](http://image.baidu.com/search/index?tn=baiduimage&fm=result&ie=utf-8&word=%60%E6%88%91%E4%BB%AC%E6%90%9C%E5%9B%BE%E7%89%87%E7%9A%84%E5%85%B3%E9%94%AE%E5%AD%97)

from requests_html import HTMLSession            #载入爬虫模块
session =HTMLSession() #创建完毕
#拿二傻子为了
response = session.get('http://image.baidu.com/search/index?tn=baiduimage&fm=result&ie=utf-8&word=二傻子')
#获取我们图片的url的正则匹配格式
img_url_regex = '"thumbURL":"{}",'
#解析并获取图片url_list
img_url_list = response.html.search_all(img_url_regex)

第四步

访问图片url并且保存下来

from requests_html import HTMLSession            #载入爬虫模块
session =HTMLSession() #创建完毕
#拿二傻子为了
response = session.get('http://image.baidu.com/search/index?tn=baiduimage&fm=result&ie=utf-8&word=二傻子')
#获取我们图片的url的正则匹配格式
img_url_regex = '"thumbURL":"{}",'
#解析并获取图片url_list
img_url_list = response.html.search_all(img_url_regex)

mun=0
for url in img_url_list:
    mun+=1
    #访问图片链接
    response= session.get(url[0])
    #保存二进制并保存至本地
    with open(f'第{mun}张.jpg','wb') as fw:
        fw.write(response.content)

第五步

类的封装

from requests_html import HTMLSession    

class BaiDuImg:
    session = HTMLSession()
    img_url_regex = '"thumbURL":"{}",'
    url=''
    img_url_list =[]

    def get_search(self):
        search=input()
        self.url=f'http://image.baidu.com/search/index?tn=baiduimage&fm=result&ie=utf-8&word={search}'

    def get_img_url_list(self):
        response=self.session.get(self.url)
        self.img_url_list = response.html.search_all(img_url_regex)

    def save_img(self):
        mun = 0
        for url in self.img_url_list:
            mun += 1
            # 访问图片链接
            response = self.session.get(url[0])
            # 保存二进制并保存至本地
            with open(f'第{mun}张.jpg', 'wb') as fw:
                fw.write(response.content)

    def run(self):
        self.get_search()
        self.get_img_url_list()
        self.save_img()

if __name__ == '__main__':
    baidu=BaiDuImg()
    baidu.run()

你可能感兴趣的:(Python实战爬虫:爬图片)