#encoding:utf-8
#!/usr/bin/env python
#@author:wei
#@file: ImageAPI.py
#@time: 2020/12/27
import requests
from bs4 import BeautifulSoup
from flask import Flask
app = Flask(__name__)

@app.route('/img/<str>')
def get_img(str):
    data = get_data(str)
    img_url = parse_data(data)
    return '<img src="'+img_url+'">'
@app.route('/imgUrl/<str>')
def get_img_url(str):
    data = get_data(str)
    img_url = parse_data(data)
    return img_url

@app.route('/')
def hello_world():

    return 'hello'


def get_data(bookName):
    # 查询
    url = 'http://www.ireader.com/index.php?ca=search.index&keyword='+bookName

    # 伪装UA
    headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
                             ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
    data = requests.get(url, headers=headers)
    #print(data.text)
    return data

# 解析数据
def parse_data(data):
    # 将网页数据转化为BeautifulSoup对象
    soup = BeautifulSoup(data.text, 'lxml')
    # print(soup)
    ul=soup.find('ul',{'class':'sResult'})
    if ul==None:
        return "404"
    li=ul.find_all('li')[0]
    img_url=li.find('img').get('src')
    # print(img_url)
    return img_url
if __name__ == '__main__':
    app.run()
