使用 Python 构建燃油价格跟踪器
原文:https://www . geesforgeks . org/build-fuel-price-tracker-use-python/
在现代生活方式中,燃料已经成为所有人类的必需品。它是我们生活方式的基础。因此,我们将使用 Python 编写一个脚本来跟踪它们的价格。
所需模块
- bs4: 美人汤(bs4)是一个从 HTML 和 XML 文件中拉出数据的 Python 库。这个模块没有内置 Python。要安装此软件,请在终端中键入以下命令。
pip install bs4
- 请求: 请求让你发送 HTTP/1.1 请求极其轻松。该模块也没有内置 Python。要安装此软件,请在终端中键入以下命令。
pip install requests
我们来看看脚本的分步执行
第一步:导入所有依赖
Python 3
# import module
import pandas as pd
import requests
from bs4 import BeautifulSoup
步骤 2: 创建一个 URL 获取函数
Python 3
# user define function
# Scrape the data
def getdata(url):
r = requests.get(url)
return r.text
步骤 3: 现在将 URL 传递给 getdata()函数,并将该数据转换为 HTML 代码
Python 3
# link for extract html data
htmldata = getdata("https://www.goodreturns.in/petrol-price.html")
soup = BeautifulSoup(htmldata, 'html.parser')
result = soup.find_all("div", class_="gold_silver_table")
print(result)
输出:
[
<表格边框=“0”cell padding =“1”cell spacing =“1”width =“100%”>
城市 t87】TD class =“heading”width =“200”>今日价格t5 /TD>₹82.03 t119】TD>Kolkata【t123 TD>₹88.73 ₹88.68 t237】tr class = " odd _ row "【t238 >t261/a>t265/TD>t49 t33\ t201】a >班加罗尔 ₹84.75 t40₹84.70 t41₹78.96 T50 ₹78.92 斋浦尔 ₹90.08 t311】TD【t312 /tr> tr class = " even _ row ">Patnat345】/TD> t347】TD>₹84.73</TD 注意:这些脚本将只提供字符串格式的原始数据,您必须根据需要打印数据。
第四步:现在,用 soup.find _ all()搜索你需要的数据。
Python 3
# Declare string var # Declare list mydatastr = '' result = [] # searching all tr in the html data # storing as a string for table in soup.find_all('tr'): mydatastr += table.get_text() # set accourding to your required mydatastr = mydatastr[1:] itemlist = mydatastr.split("\n\n") for item in itemlist[:-5]: result.append(item.split("\n")) result
输出:
第 4 步:制作一个数据框来显示你的结果。
Python 3
# Calling DataFrame constructor on list df = pd.DataFrame(result[:-8]) df
完整代码:
Python 3
# import module import requests import pandas as pd from bs4 import BeautifulSoup # link for extract html data def getdata(url): r = requests.get(url) return r.text htmldata = getdata("https://www.goodreturns.in/petrol-price.html") soup = BeautifulSoup(htmldata, 'html.parser') # Declare string var # Declare list mydatastr = '' result = [] # searching all tr in the html data # storing as a string for table in soup.find_all('tr'): mydatastr += table.get_text() # set accourding to your required mydatastr = mydatastr[1:] itemlist = mydatastr.split("\n\n") for item in itemlist[:-5]: result.append(item.split("\n")) # Calling DataFrame constructor on list df = pd.DataFrame(result[:-8]) df
输出:
版权属于:月萌API www.moonapi.com,转载请注明出处