gpt4 book ai didi

python - 当用户输入有效 URL 或不使用 PYTHON/Flask 时,如何为用户设置代码?

转载 作者:行者123 更新时间:2023-11-28 04:59:09 24 4
gpt4 key购买 nike

我想知道我需要用 Python 或 Flask 采用哪种方法来完成以下任务:

  • 检查网址是否有效
  • 如果有效则返回该页面及其子页面上所有链接的列表

我的编辑器很棒,我在 Windows Powershell 下运行它

现在我的代码显示了这个:

enter image description here

因此,当您输入搜索时,它会转到一个新页面并显示结果(例如:ddddd)

enter image description here

但我想检查 URL 是否有效,如果有效则返回该页面及其子页面上所有链接的列表,如下所示:

enter image description here

对编程世界的新手有什么想法吗?(现在不是很新,还有很多东西要学..)

感谢您的帮助。

这里是我的代码谁带来了这个结果(它的工作):

因此,我的 .py 中的项目文件夹设置为 Flask,模板文件夹中为 .html。


Python文件

# -*- coding: utf-8 -*-
from flask import Flask, render_template, request
import re

app = Flask (__name__)

@app.route("/")
def index():
return render_template('index.html')

@app.route('/search', methods=['POST', 'GET'])
def search():
error = True
if request.method == 'POST':
return request.form['urlsearch']
else:
return request.args.get('urlsearch')

if __name__ == "__main__":
app.run()

HTML 文件

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>URL TEST</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>

<h1 style="color:orange;">You can put your URL here :</h1>
{{ a_variable }}

<form method="get" action="/search">
<p>Please Input an URL below : </p>
<input type="text" name="urlsearch" />
<input type="submit" value="Search" />
</form>
</body>
</html>

最佳答案

您可以使用 mechanize :

from mechanize import Browser

br = Browser()
r = br.open("http://www.example.com/")

if r.code == 200:
for link in br.links():
print link
else:
print "Error loading page"

urllib2BeautifulSoup

from BeautifulSoup import BeautifulSoup
import urllib2

html_page = urllib2.urlopen("http://www.example.com")
if html_page.getcode() == 200:
soup = BeautifulSoup(html_page)
for link in soup.findAll('a'):
print link.get('href')
else:
print "Error loading page"

我以前用 Flask 的工作不多,但试试这个:

据我所知,urlsearch 是您从表单中获取的 URL,因此请对其进行检查

@app.route('/search', methods=['POST', 'GET'])
def search():
error = True
if request.method == 'POST':
return request.form['urlsearch']
else:
br = Browser()
r = br.open(request.args.get('urlsearch'))

if r.code == 200:
return br.links()
else:
return "Error loading page"

关于python - 当用户输入有效 URL 或不使用 PYTHON/Flask 时,如何为用户设置代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18141698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com