【问题标题】:Blocked by CORS policy: No"Access-Control-Allow-Origin" Using Flask被 CORS 策略阻止:No"Access-Control-Allow-Origin" Using Flask
【发布时间】:2020-12-18 11:16:29
【问题描述】:

我正在尝试制作一个烧瓶 Web 应用程序,它可以下载整个网页并在 localhost 上呈现它以裁剪元素。请求模块从站点获取所有数据,除了它所说的一些数据

来源“http://127.0.0.1:5000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

以下是我为烧瓶应用程序编写的代码。我也尝试过flask_cros,但似乎没有帮助。

from flask_socketio import SocketIO, emit
from flask_session import Session
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse
from flask_cors import CORS,cross_origin
app= Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
app.config["CORS_HEADERS"]="Content-Type"
socketio=SocketIO(app)
session=Session(app)
cors = CORS(app)
dir= os.path.abspath(os.getcwd())
@app.route("/")
def index():
   
   return render_template("index.html")
@app.route("/crop",methods=["POST"])
@cross_origin()
def crop():
   if request.method=="POST":
       outfile=open("result.txt","w")
       outfile.write("<iframe>")
       outfile.close()
       dummy= open("templates/down.html",'w')
       dummy.close()
       global link
       link = str(request.form.get("url"))
       
       r= requests.get(link,allow_redirects=True,headers={"User-Agent":"Chrome/42.0.2311.135"})
       if r.status_code==405:
           return render_template("exception.html")
       soup = BeautifulSoup(r.content,"html.parser")
       outfile=open("links.html","w")
       for a in soup.findAll("link",attrs={'href':True},rel="stylesheet"):
           if a['href'][0:4]!="http":
               dom= urlparse(link)
               wurl=dom.scheme+"://"+dom.netloc
               r1=requests.get(wurl+a['href'],headers={"User-Agent":"Chrome/42.0.2311.135"})
               if r1.status_code==200:    
                   a['href']= wurl + a['href']

                   print(a)
                   outfile.write(str(a))
               else:
                    a['href']= link + a['href']
                    outfile.write(str(a))
           else:
               outfile.write(str(a))
           
       outfile.close()
       
      
       body= soup.prettify("utf-8")
    
       with open("templates/down.html",'wb') as file:
           file.write(body)
       return render_template("base.html") ```

【问题讨论】:

    标签: python flask web-scraping cors


    【解决方案1】:

    您想让烧瓶发送丢失的标头:

    Access-Control-Allow-Origin: *
    

    【讨论】:

    • r= requests.get(link,allow_redirects=True,headers={"User-Agent":"Chrome/42.0.2311.135","Access-Control-Allow-Origin":'*'}) 我把它加到了行中,但是没有用。
    • Flask 需要将其作为响应头发送。
    猜你喜欢
    • 2020-01-18
    • 2019-04-26
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 2019-08-09
    • 2021-02-01
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多