【问题标题】:covert string to int but string is html based (python3)将字符串转换为 int 但字符串是基于 html 的(python3)
【发布时间】:2022-01-16 20:07:41
【问题描述】:

我正在尝试制作一个机器人,它从谷歌获取 btc 价格数据并与另一个网站进行比较,但我找不到一种方法可以让从 html 打印的数字变成整数(所以我可以比较数字)。

错误:

<ipython-input-37-58a648f164e1> in <module>()
     11 tring = text.replace(" United States Dollar", "")
     12 
---> 13 tle = int(tring)
     14 
     15 print(tle)

ValueError: invalid literal for int() with base 10: '43,020.80'

代码:

#make request to website
HTML = requests.get(url)

#parse the html
soup = BeautifulSoup(HTML.text, 'html.parser') 


text = soup.find("div", attrs={'class':'BNeawe iBp4i AP7Wnd'}).find("div", attrs={'class':'BNeawe iBp4i AP7Wnd'}).text

tring = text.replace(" United States Dollar", "")

tle = int(tring)

print(tle)```

【问题讨论】:

  • 该数据表示的不是整数而是浮点数。您需要将字符串转换为float。但首先,有几种方法可以处理带有千位分隔符的数字:stackoverflow.com/questions/6633523/…

标签: python html python-3.x beautifulsoup


【解决方案1】:

如果您只对“43,020.80”的整数部分感兴趣,那么:

int(float('43,280.50'.replace(',','')))) == 43280

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2018-05-23
    • 2013-03-02
    • 2011-10-02
    • 2011-03-06
    相关资源
    最近更新 更多