大家好!今天我要教大家用Python做一个超酷的“融合门户”小项目。什么叫融合门户呢?简单来说,就是一个能整合多个功能的小网站,比如新闻、天气预报、股票行情啥的。
先说下我们的目标:创建一个网页,上面有三个模块——新闻展示、天气查询、还有股票行情。听起来是不是很有趣?
好了,废话不多说,我们直接进入正题!
首先,我们需要安装一些库。打开终端,输入以下命令:
pip install flask requests beautifulsoup4
这里用到了Flask框架来搭建Web服务器,requests用来发送HTTP请求获取数据,beautifulsoup4用来解析HTML页面。
接下来是我们的代码部分。我将逐步解释每一部分的功能:
from flask import Flask, render_template import requests from bs4 import BeautifulSoup app = Flask(__name__) @app.route('/') def home(): # 新闻部分 news_url = 'https://news.ycombinator.com/' news_response = requests.get(news_url) soup = BeautifulSoup(news_response.text, 'html.parser') news_titles = [tag.text for tag in soup.select('.storylink')[:5]] # 天气部分 weather_url = 'https://www.weather.com.cn/weather/101010100.shtml' weather_response = requests.get(weather_url) soup_weather = BeautifulSoup(weather_response.text, 'html.parser') temperature = soup_weather.select('.tem')[0].text.strip() weather_status = soup_weather.select('.wea')[0].text.strip() # 股票部分 stock_url = 'https://finance.sina.com.cn/' stock_response = requests.get(stock_url) soup_stock = BeautifulSoup(stock_response.text, 'html.parser') stock_price = soup_stock.select('.cboth')[0].text.strip() return render_template('index.html', news=news_titles, temp=temperature, status=weather_status, price=stock_price) if __name__ == '__main__': app.run(debug=True)
这段代码首先定义了一个Flask应用,然后在主页上展示了新闻、天气和股票信息。我们使用requests库从网络抓取数据,并用BeautifulSoup解析HTML。
最后一步是创建HTML模板文件`index.html`,用于显示这些数据:
融合门户 欢迎来到融合门户 今日新闻 {% for title in news %} {{ title }} {% endfor %} 天气状况 温度: {{ temp }} 天气: {{ status }} 股票行情 {{ price }}
到这里,我们的融合门户就完成了!你可以运行这个程序,然后在浏览器中访问http://127.0.0.1:5000/,就能看到效果啦!
总结一下,我们今天学习了如何结合Flask、requests和BeautifulSoup来快速构建一个融合门户网站。希望你们都能动手试试看,玩得开心!
]]>