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

本站现有博文337篇,共被浏览953635次

本站已经建立2663天!

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