EADST

Python: Obtain Baidu Images Using Web Crawler

Python: Obtain Baidu Images Using Web Crawler.

Here is the main code.

# -- coding: utf-8 --
import os
import re
import time
import requests

class CarCollect():

def __init__(self, path='./name.txt'):
    self.num = 1
    self.class_number = 0
    self.line_list = []
    with open(path, encoding='utf-8') as file:
        self.line_list = [k.strip() for k in file.readlines()]
        self.class_number = int(self.line_list[0])
        self.line_list = self.line_list[1:]

def dowmload_picture(self, html, keyword, save_path):
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)  # get image url
    print('Finding keyword: ' + keyword + ' images, start downloading...')
    for each in pic_url:
        print('='*60)
        print('Downloading ' + keyword + ' number ' + str(self.num) + ' image, url: ' + str(each))
        try:
            if each:
                pic = requests.get(each, timeout=7)
                string = save_path + r'\\' + keyword + '_' + str(self.num) + '.jpg'
                if len(pic.content) > 10000: # img size > 10k
                    with open(string, 'wb') as fp:
                        fp.write(pic.content)
                        self.num += 1
        except BaseException:
            print('error, cannot download')
        if self.num > self.class_number:
            break

def __call__(self):
    headers = {
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0',
        'Upgrade-Insecure-Requests': '1'
    }
    session = requests.Session()
    session.headers = headers

    for word in self.line_list:
        # create a folder
        save_path = word + '_file'
        time_now = time.strftime("%Y%m%d_%H%M%S", time.localtime())
        save_path += "_" + time_now
        os.mkdir(save_path)
        # get images
        url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='
        image_number = 0
        self.num = 1
        while image_number < self.class_number:
            try:
                result = session.get(url + str(image_number), timeout=10, allow_redirects=False)
                self.dowmload_picture(result.text, word, save_path)
            except:
                print('Internet error')
            image_number += 60

if name == 'main': path = './keywords.txt' car_collect = CarCollect(path) car_collect() print('Done.')

Here is the text file, keywords.txt. The first line is the number we want to obtain from each keyword. The following lines are the keywords.

20
Dog
Cat

相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
Datetime Shortcut TSV Base64 Card 自我改进 llama.cpp Land git XML CTC Freesound Pytorch VSCode WAN 个人博客 Markdown UI Translation Baidu LLAMA 财报 Git Gemma SPIE tqdm 腾讯云 Claude Distillation FP16 scipy 版权 Streamlit Django logger 多线程 Rebuttal NameSilo Linux GGML ResNet-50 Input Llama Qwen Ubuntu 音频 长程智能体 国产算力 LaTeX Domain Miniforge PDB 高效序列架构 CUDA CAM transformers Vmess git-lfs LLM Nginx Bitcoin Hilton 净利润 AI Magnet FP8 Food 域名 多进程 Pandas Bipartite 图形思考法 SQL TensorRT Cloudreve NLTK 递归学习法 Attention GIT Interview Use printf Quantize 强化学习 Knowledge HaggingFace Google IndexTTS2 Proxy Paper Password Template GoogLeNet Docker torchinfo diffusers Diagram 报税 人工审批 Video uWSGI 图标 LoRA Statistics Agent Ptyhon VPN SVR PyTorch YOLO 具身控制 EXCEL Disk Harness Tracking 论文速读 继承 OpenCV Logo Anaconda Breakpoint VGG-16 API Safetensors Search Pickle 长期记忆 BTC Mixtral Transformers RGB TensorFlow 论文 InvalidArgumentError hf SQLite Michelin 阿里云 Bert Random LeetCode Plate Math OCR Firewall 实时视觉生成 Image2Text 搞笑 icon PyCharm COCO CEIR Data 云服务器 GPT4 Tensor Animate WebCrawler GPTQ FP64 信用卡 Qwen2.5 Zip 证件照 ONNX ModelScope Qwen2 QWEN FlashAttention FP32 OpenAI Numpy News ms-swift BeautifulSoup Python Paddle DeepStream Agent设计模式 FastAPI v0.dev Website 飞书 API网关 Permission Pillow PIP Dataset Clash tar Color CV Plotly Github Hotel Jupyter 关于博主 ChatGPT mmap CLAP MD5 UNIX uwsgi 算法题 Web Review CSV Excel Jetson BF16 HuggingFace Jev 多智能体协作 TTS 公式 RL 顶会 Sklearn Bin Tiktoken Augmentation PDF Quantization Hungarian 签证 v2ray NLP C++ Algorithm CC Windows Heatmap Crawler Conda Vim SAM 第一性原理 RAR JSON ReAct DeepSeek XGBoost
站点统计

本站现有博文343篇,共被浏览1065994次

本站已经建立2733天!

热门文章
文章归档
回到顶部