[英]passing a website as a parameter in REST API python; error with "/"
我正在尝试将网站作为参数传递。 如果网站中没有“/”,它就可以工作。 例如: http : //192.168.1.156 : 2434/ www.cookinglight.com 为其页面上的所有图像抓取烹饪灯; 但是,如果我传入http://192.168.1.156:2434/https://www.cookinglight.com/recipes/chicken-apple-butternut-squash-soup然后我得到一个无效的响应。 这是我当前的代码:
import json
from flask import Flask, render_template
from imagescraper import image_scraper
app = Flask(__name__)
@app.route("/", methods = ['GET'])
def home():
return render_template('index.html')
@app.route("/<site>", methods = ['GET'])
def get_image(site):
return json.dumps(image_scraper(site))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=2434, debug=True)
import requests
from bs4 import BeautifulSoup
def image_scraper(site):
"""scrapes user inputed url for all images on a website and
:param http url ex. https://www.cookinglight.com
:return dictionary key:alt text; value: source link"""
search = site.strip()
search = search.replace(' ', '+')
website = 'https://' + search
response = requests.get(website)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')
# create dictionary to add image alt tag and source link
images = {}
for img in img_tags:
try:
name = img['alt']
link = img['src']
images[name] = link
except:
pass
return images
我试过 urrllib 但没有任何成功。 任何帮助将不胜感激! 我是学生所以还在学习!!
Flask
使用/
作为参数之间的分隔route("/<arg1>/<arg2>/<arg3>")
- 因此您可以创建route("/<arg1>/<arg2>/<arg3>")
并获取变量arg1
、 arg2
、 arg3
- 当您尝试将 url 与/
一起使用时它试图找到像route("/<arg1>/<arg2>/<arg3>")
这样的route("/<arg1>/<arg2>/<arg3>")
如果您想使用/
作为单个参数的一部分,而不是作为参数之间的分隔符,那么您需要<path:site>
。
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello World"
@app.route("/<path:site>")
def get_image(site):
return f"OK: {site}"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=2434)#, debug=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.