嘿,所以我试图获取当前的油价,然后对其进行一些数学计算以进行硬件作业。我无法在网站上找到我需要的号码。 这是我的代码
# Module oilcost.py to compute the delivery cost for home heating oil.
# Assume your delivery company charges a 10% fee on top of the price
# per gallon. The module should take one command line argument
# indicating the number of gallons needed and should output the
# total cost.
import sys
import re
import urllib
def getOilPrice(url):
f = urllib.urlopen(url)
html=f.read()
f.close()
match = re.search(r'<span class="dailyPrice">( d+.? d+)</span>', html)
return match.group(1) if match else '0'
def outputPrice(oilprice, gallons, total):
print 'The current oil price is $ %s' %oilprice
def main():
url = 'http://www.indexmundi.com/commodities/?commodity=heating-oil'
oilprice = float(getOilPrice(url)) # Create this method
gallons = float(sys.argv[1]) # Get from command line
total = (gallons * 1.1) * oilprice
outputPrice(oilprice, gallons, total) # Create this method
if __name__ == '__main__':
main()
谁能告诉我我做错了什么?
最佳答案
Parsing html is notiorusly fraught with peril;但对于家庭作业来说,这可能并不那么重要;这是学习正则表达式的好机会。
上线:
match = re.search(r'<span class="dailyPrice">( d+.? d+)</span>', html)
# ^ ^
你有一些d
,它们将与文字字母d
匹配。您的意思可能是 \d
(这是一个反斜杠)吗?
关于用于搜索 url 的 Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9538945/