用于搜索 url 的 Python 代码

标签 python

嘿,所以我试图获取当前的油价,然后对其进行一些数学计算以进行硬件作业。我无法在网站上找到我需要的号码。 这是我的代码

    # 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/

相关文章:

python - Pandas:将列添加到多索引以实现任意深度的索引级别

python - 我收到错误消息 : TypeError: unsupported operand type(s) for %: 'DeferredAttribute' and 'dict' in django

python - 抓取附有张量名称的张量索引

python - 基于客户端IP地址的 Pyramid 授权

python - 为每组连续增加的日期添加行号列

Python 线程通信不起作用

python - 使用特定列估算 scikit-learn 中的分类缺失值

python - 上传文件在谷歌应用程序引擎中不起作用

python - odoo10如何在1个字段中构建2个onchange函数

python - 如何查看 html 选择器中的隐藏内容?