要做一个图片网站,需要导入很多图片。从SEO角度来讲,就需要给每一张图片添加文字说明。然而图片太多,人工做这件事情就会变得特别枯燥无味了。我又想到了python3。基本思路是,首先找到一个识图IPI,然后一张一张的提交图片过去,然后读取识别的内容。具体代码如下:

from selenium import webdriver
import time,bs4,os,csv,json,re,requests
from selenium.webdriver.chrome.options import Options

def to_url(key):
    key=re.sub(' +','_',key)
    url = 'https://cn.bing.com/images/search?&q='+key+'&qft=+filterui:photo-photo+filterui:imagesize-large&FORM=IRFLTR'
    return url

def pro_urls(url):
    opt = webdriver.ChromeOptions()
    #opt.set_headless() #老版本设置无头
    opt.add_argument("--headless") #新版本设置无头
    opt.add_argument("--disable-gpu")
    driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe',options=opt) #驱动器路径
    while True:
        try:
            print('...')
            driver.get(url)
            break
        except:
            print('链接失败,重试中。。。')
            print('')

    time.sleep(1)
    a=0
    while a<3:
        #下拉鼠标
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight); var lenOfPage=document.body.scrollHeight; return lenOfPage;")
        time.sleep(2)
        a=a+1

    html=driver.page_source    
    bs=bs4.BeautifulSoup(html,'html.parser')    
    prourls=bs.select('.iusc')
    driver.quit()
    for prourl in prourls:
        prourl=json.loads(prourl.get('m'))['murl']
        shitu(prourl)
        #print(prourl)

def shitu(imgurl):
    #https://www.captionbot.ai/ 在线识图工具
    url='https://captionbot.azurewebsites.net/api/messages?language=en-US'
    data={
        "Type":"CaptionRequest",
        "Content":imgurl
        }
    while True:
        try:
            print('......')
            r=requests.post(url,data=data)
            break
        except:
            print('识图失败,重试中。。。。')
            print('')
    des=r.text
    #des1=re.sub('我无法完全理解这副图片,但是我看到了|。|我觉得这是','',des) #中文版
    des1=re.sub('I am not really confident, but I think it \'s a|I think it\'s a ','',des)
    
    #print('原文:',des)
    print('图片URL:',imgurl)
    print('这张图片的内容是:',des1)
        

key=input('请输入关键词:')
key=str(key)
url=to_url(key)
pro_urls(url)