用python代码制作一个爬取内蒙古师范大学新闻列表的 Flask 网页,要求有输入爬取的网页这个按钮
时间: 2024-05-04 13:16:22 浏览: 13
好的,以下是可以实现您的需求的代码,需要安装 Flask 和 requests 模块:
```python
from flask import Flask, render_template, request
import requests
from bs4 import BeautifulSoup
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/crawl', methods=['POST'])
def crawl():
url = request.form['url']
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
news_list = []
for item in soup.select('ul.list li'):
title = item.select_one('a')['title']
link = item.select_one('a')['href']
pub_date = item.select_one('span').text
news_list.append({'title': title, 'link': link, 'pub_date': pub_date})
return render_template('result.html', news_list=news_list)
if __name__ == '__main__':
app.run(debug=True)
```
在项目目录下创建两个 HTML 模板文件 index.html 和 result.html。index.html 用来展示一个输入框和一个提交按钮,result.html 用来展示爬取结果。
index.html:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>内蒙古师范大学新闻列表爬虫</title>
</head>
<body>
<h1>内蒙古师范大学新闻列表爬虫</h1>
<form method="POST" action="/crawl">
<label for="url">请输入需要爬取的新闻列表页地址:</label>
<input type="text" id="url" name="url">
<input type="submit" value="爬取">
</form>
</body>
</html>
```
result.html:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>爬取结果</title>
</head>
<body>
<h1>爬取结果</h1>
<table>
<thead>
<tr>
<th>标题</th>
<th>链接</th>
<th>发布时间</th>
</tr>
</thead>
<tbody>
{% for item in news_list %}
<tr>
<td>{{ item.title }}</td>
<td><a href="{{ item.link }}">{{ item.link }}</a></td>
<td>{{ item.pub_date }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
```
将以上代码保存成一个 Python 文件,比如 app.py,运行并访问 http://127.0.0.1:5000 即可看到页面。