python默认打开浏览器_Python-Flask-以默认浏览器打开网页

本文介绍了一个Python项目,该项目分为两部分:爬虫和使用Flask展示信息。在展示部分,作者遇到一个问题,即Flask应用运行时会在默认浏览器中打开两个页面。问题可能源于`run()`方法在新线程中启动了Flask。代码示例展示了如何连接SQLite数据库并使用Flask渲染模板。目前,目标是解决导致浏览器打开两次的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在用Python做一个小项目。它分为两部分。

第一部分负责抓取网页并提取一些信息并将其插入数据库。

第二部分是利用数据库来呈现这些信息。

两部分共享数据库。在第二部分中,我使用Flask框架将信息显示为html,并进行一些格式化、样式设置等,使其看起来更清晰。

两部分的源文件都在同一个包中,但要正确运行此程序,用户必须分别运行爬网程序和结果演示程序,如下所示:

python crawler.py

然后

python presenter.py

一切都很好,除了一件事。我presenter要做的是创建html格式的结果,并在用户的默认浏览器中打开带有结果的页面,但它总是打开两次,这可能是由于run()方法的存在,该方法在新线程中启动Flask,并且对我来说事情变得模糊。我不知道该怎么做才能使presenter.py在运行后只打开一个选项卡/窗口。

以下是我的代码片段:from flask import Flask, render_template

import os

import sqlite3

# configuration

DEBUG = True

DATABASE = os.getcwd() + '/database/database.db'

app = Flask(__name__)

app.config.from_object(__name__)

app.config.from_envvar('CRAWLER_SETTINGS', silent=True)

def connect_db():

"""Returns a new connection to the database."""

try:

conn = sqlite3.connect(app.config['DATABASE'])

return conn

except sqlite3.Error:

print 'Unable to connect to the database'

return False

@app.route('/')

def show_entries():

u"""Loads pages information and emails from the database and

inserts results into show_entires template. If there is a database

problem returns error page.

"""

conn = connect_db()

if conn:

try:

cur = connect_db().cursor()

results = cur.execute('SELECT url, title, doctype, pagesize FROM pages')

pages = [dict(url=row[0], title=row[1].encode('utf-8'), pageType=row[2], pageSize=row[3]) for row in results.fetchall()]

results = cur.execute('SELECT url, email from emails')

emails = {}

for row in results.fetchall():

emails.setdefault(row[0], []).append(row[1])

return render_template('show_entries.html', pages=pages, emails=emails)

except sqlite3.Error, e:

print ' Exception message %s ' % e

print 'Could not load data from the database!'

return render_template('show_error_page.html')

else:

return render_template('show_error_page.html')

if __name__ == '__main__':

url = 'http://127.0.0.1:5000'

webbrowser.open_new(url)

app.run()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值