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

本站现有博文338篇,共被浏览972308次

本站已经建立2685天!

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