【发布时间】:2021-12-18 19:57:25
【问题描述】:
我正在尝试将网站作为参数传递。如果网站中没有“/”,它就可以工作。例如: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
我尝试了 urlllib,但没有任何成功。任何帮助将不胜感激!我是学生所以还在学习!!
更新:
我相信这是 stackoverflow 帖子中描述的问题
【问题讨论】:
-
对网站 URL 进行 URL 编码。
-
如果您使用
/发送网址,那么它会尝试查找类似route("/<arg1>/<arg2>/<arg3>")的路由,这会产生问题 - 您必须将/转换为代码%hex。或以/?site=your_url发送,然后以request.args["site"]获取它 -
如果您收到
invalid response,则将此有问题的回复(不在 cmets 中)显示为文本。我们不会运行代码来查看invalid response并且我们无法在您的脑海中阅读。 -
总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是截图,不是链接到外部门户)有问题(不是评论)。还有其他有用的信息。
-
这是错误:未找到服务器上未找到请求的 URL。如果您手动输入了 URL,请检查您的拼写并重试。