Python ValueError:int() 的无效文字,基数为 10:'196.41'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47762060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:21:35  来源:igfitidea点击:

ValueError: invalid literal for int() with base 10: '196.41'

pythonweb-scrapingbeautifulsoupdata-sciencevalueerror

提问by uzdisral

I don't understand why it works with different scenarios, but not with this one. Basically, some gentleman helped me out HEREwith improving my code to scrape weather, which works perfectly. I then tried to do the same to scrape an ETH value which is in a span tag <span class="text-large2" data-currency-value="">$196.01</span>. So, I followed the same technique in the code, replaced the fields, and was hoping for it to work.

我不明白为什么它适用于不同的场景,但不适用于这个场景。基本上,一些绅士在这里帮助我改进了我的代码以刮取天气,这非常有效。然后我尝试做同样的事情来刮取 span 标签中的 ETH 值<span class="text-large2" data-currency-value="">$196.01</span>。所以,我在代码中采用了相同的技术,替换了字段,并希望它能够工作。

The code is here:

代码在这里:

import requests
from BeautifulSoup import BeautifulSoup
import time

url = 'https://coinmarketcap.com/currencies/litecoin/'

def ltc():
    while (True):
        response = requests.get(url)
        soup = BeautifulSoup(response.content)
        price_now = int(soup.find("div", {"class": "col-xs-6 col-sm-8 col-md-4 text-left"}).find(
        "span", {"class": "text-large2"}).getText())
        print(u"LTC price is: {}{}".format(price_now))
        # if less than 150
        if 150 > price_now:
            print('Price is Low')
        # if more than 200
        elif 200 < price_now:
            print('Price is high')

if __name__ == "__main__":
    ltc()

The output looks like this:

输出如下所示:

Traceback (most recent call last):
  File "test2.py", line 24, in <module>
    ltc()
  File "test2.py", line 13, in ltc
    "span", {"class": "text-large2"}).getText())
ValueError: invalid literal for int() with base 10: '196.01'

Then, I finally tried it this way; but from here I get false positives, but no errors. It prints whatever it wants

然后,我终于这样试过了;但从这里我得到误报,但没有错误。它打印任何它想要的

import requests
from bs4 import BeautifulSoup
import time

url = 'https://coinmarketcap.com/currencies/litecoin/'

def liteCoin():
    while (True):
        response = requests.get(url)
        html = response.text
        soup = BeautifulSoup(html, 'html.parser')
        value = soup.find('span', {'class': 'text-large2'})
        print(''.join(value.stripped_strings))
        if 150 > value:         # if less than 150
            print('Price is Low!')
        elif 200 < value:       # if more than 200
            print('Price is High')
        else:
            print('N/A')
        time.sleep(5)

if __name__ == "__main__":
    liteCoin()

Would the problem be that the value of the ETH has a $sign inside the span tag? And, that way the program doesn't know what to do with string?

问题是 ETH 的价值$span tag. 而且,这样程序不知道如何处理字符串?

回答by Rob?

First, let's simplify your sample program:

首先,让我们简化您的示例程序:

>>> int('196.01')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '196.01'

One cannot convert the string '196.01'to an integer number.

不能将字符串转换为'196.01'整数。

Try this:

尝试这个:

>>> int(float('196.01'))
196

Moving from the simple back to the complex, we can do this:

从简单回到复杂,我们可以这样做:

#UNTESTED
price_now = int(float(soup.find("div", {"class": "col-xs-6 col-sm-8 col-md-4 text-left"}).find(
    "span", {"class": "text-large2"}).getText()))

回答by Dan-Dev

You need to understand types in Python you are getting a float not an int and you need to cast the float to a string to print it. So there are two changes needed.

您需要了解 Python 中的类型,您得到的是浮点数而不是整数,您需要将浮点数转换为字符串以打印它。因此,需要进行两个更改。

    price_now = float(soup.find("div", {"class": "col-xs-6 col-sm-8 col-md-4 text-left"}).find("span", {"class": "text-large2"}).getText())
    print(u"LTC price is: {}".format(str(price_now)))

Outputs:

输出:

LTC price is: 195.44
LTC price is: 195.44