爬百度图片

# -*- coding: utf-8 -*-
"""根据搜索词下载百度图片"""
import re
import sys
import urllib
import os
import requests


def get_onepage_urls(onepageurl):
    """获取单个翻页的所有图片的urls+当前翻页的下一翻页的url"""
    if not onepageurl:
        print('已到最后一页, 结束')
        return [], ''
    try:
        html = requests.get(onepageurl)
        html.encoding = 'utf-8'
        html = html.text
    except Exception as e:
        print(e)
        pic_urls = []
        fanye_url = ''
        return pic_urls, fanye_url
    pic_urls = re.findall('"objURL":"(.*?)",', html, re.S)
    fanye_urls = re.findall(re.compile(r'<a href="(.*)" class="n">下一页</a>'), html, flags=0)
    fanye_url = 'http://image.baidu.com' + fanye_urls[0] if fanye_urls else ''
    return pic_urls, fanye_url


def down_pic(pic_urls):
    """给出图片链接列表, 下载所有图片"""
    save_path = './DataSet/' + keyword
    if not os.path.exists(save_path):
        print("Selected folder not exist, try to create it.")
        os.makedirs(save_path)
    for i, pic_url in enumerate(pic_urls):
        try:
            pic = requests.get(pic_url, timeout=5)
            string = save_path + '/' + str(i + 1) + '.jpg'
            with open(string, 'wb') as f:
                f.write(pic.content)
                print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
        except Exception as e:
            print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
            print(e)
            continue


if __name__ == '__main__':
    keyword = '晴天'  # 关键词, 改为你想输入的词即可, 相当于在百度图片里搜索一样
    url_init_first = r'http://image.baidu.com/search/flip?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1497491098685_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&ctd=1497491098685%5E00_1519X735&word='
    url_init = url_init_first + urllib.parse.quote(keyword, safe='/')
    all_pic_urls = []
    onepage_urls, fanye_url = get_onepage_urls(url_init)
    all_pic_urls.extend(onepage_urls)

    fanye_count = 0  # 累计翻页数
    while 1:
        onepage_urls, fanye_url = get_onepage_urls(fanye_url)
        fanye_count += 1
        print('第%d页' % fanye_count)
        if fanye_url == '' and onepage_urls == []:
            break
        all_pic_urls.extend(onepage_urls)

    down_pic(list(set(all_pic_urls)))

如果需要下载百度图片时,仅仅是需要主程序第一行关键词修改为自己需要的关键词即可。
如果想详细了解爬虫需要的库以及详细过程可以参考的链接:python——爬虫示例读取豆瓣电影数据

### 使用Python实现批量百度图片 为了实现这一目标,可以基于HTTP请求库`requests`获取网页内容,并使用HTML解析器如`BeautifulSoup`来分析页面结构,进而定位到图片链接。考虑到反机制的存在,在发送请求时应适当设置headers模拟浏览器行为[^1]。 #### 准备工作 首先安装必要的第三方模块: ```bash pip install requests beautifulsoup4 lxml ``` #### 获取图片链接列表 构建函数用于发起GET请求至指定关键词对应的百度图片搜索页,随后解析返回的HTML文档以收集img标签中的src属性值作为实际图像地址: ```python import requests from bs4 import BeautifulSoup def get_image_urls(keyword, max_num=30): base_url = "https://image.baidu.com/search/index?tn=baiduimage&word=" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', } image_urls = [] while len(image_urls)<max_num: url = f"{base_url}{keyword}&pn={len(image_urls)}" response = requests.get(url=url, headers=headers) soup = BeautifulSoup(response.text,'lxml') items = soup.find_all('img', class_='main_img img-hover') for item in items[:min(max_num-len(image_urls),len(items))]: src=item['data-imgurl']if' data-imgurl'in item.attrs else item['src'] if not src.startswith('http'): continue image_urls.append(src) return image_urls ``` 此部分逻辑遵循了基本的网络爬虫开发模式,即构造URL、发出请求、接收响应并从中抽取所需信息。 #### 下载图片文件 定义另一个辅助方法负责下载单张照片,并将其存储于本地磁盘目录下: ```python import os.path as osp import urllib.request def download_images(urls, save_dir='./images/', prefix='baidu_'): if not osp.exists(save_dir):os.makedirs(save_dir) count = 0 for idx,url in enumerate(urls,start=1): try: ext=url.split('.')[-1].lower() filename=f'{prefix}{count}.{ext}' filepath=osp.join(save_dir,filename) opener=urllib.request.build_opener() opener.addheaders=[('User-agent','Mozilla/5.0')] urllib.request.install_opener(opener) urllib.request.urlretrieve(url,filepath) print(f'Downloaded {idx}/{len(urls)} images.') count+=1 except Exception as e: print(e) pass return count ``` 上述代码片段展示了如何通过迭代访问先前获得的一系列网址完成资源下载操作;同时注意异常处理确保程序稳定性[^4]。 最后组合以上两个功能即可形成完整的解决方案框架,允许用户输入感兴趣的主题名称从而启动自动化采集过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值