【问题标题】:Python flask requests load pagePython烧瓶请求加载页面
【发布时间】:2016-05-05 08:50:20
【问题描述】:
创建从我的服务器加载页面的脚本(使用服务器 IP 等) - 一切正常,但如果我想点击任何链接,我会进入 404 错误页面,因为链接是 - 类似这样的东西:
...37.139.17.81:5000/html/privacy-check.php
我的代码:
from flask import Flask
import requests
application = Flask(__name__)
@application.route("/")
def hello():
result = requests.get("http://ipinfo.info/index.php")
return result.content
if __name__ == "__main__":
application.run(host='0.0.0.0')
这是一个活生生的例子:
http://37.139.17.81:5000/
如何解析点击 URL 并获取此链接内容?
【问题讨论】:
标签:
python
flask
python-requests
anonymous
【解决方案1】:
您基本上是在尝试使您的页面充当远程页面的代理。为了完全做到这一点,您需要处理远程页面中的所有链接。
例如,如果有像/something/something 这样的链接,flask 会自动尝试将其与本地 url (http://yourserver.com/something/something) 匹配。鉴于您只定义了一个路由(“/”),应用程序将确定任何其他页面不存在并返回 404。
要正确处理此问题,您可以尝试以下方法:
import urlparse
@application.route("/")
@application.route("/<url:path>")
def hello(url=None):
baseurl = "http://ipinfo.info/"
if not url:
result = requests.get(urlparse.urljoin(baseurl,"index.php"))
return result.content
else:
result = requests.get(urlparse.urljoin(baseurl,url))
return result.content
警告:这种方法可能会在各种情况下中断(例如加载 css 和 js),因此您可能需要在页面加载后检查结果。
【解决方案2】:
对于href="/html/privacy-check.php",你应该这样做
@application.route("/html/privacy-check.php")
def hello():
result = requests.get("http://ipinfo.info/index.php")
return result.content
由于它在您的服务器上找不到任何与 /html/privacy-check.php 匹配的 url,因此会抛出 404 错误。
【解决方案3】:
您的“脚本”是在本地服务器 http://37.139.17.81:5000/ 上运行的烧瓶应用程序。
当您单击从其他站点加载的页面上的链接时,您的烧瓶应用程序合理地认为它是烧瓶应用程序中页面的链接,因此会尝试在本地应用程序上加载该页面。
烧瓶应用程序在本地服务器上查找链接可能是因为您加载的页面上的链接是相对链接。
要解析链接,您可以使用类似urlparse
from urlparse import urlparse
o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
o
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
params='', query='', fragment='')
我不得不问你为什么要尝试将 php 页面加载到烧瓶应用程序中?