我正在用 Python 编写一个小机器人,但遇到了问题。这似乎是一个常见问题,但我从未见过它在我所处的情况下被问到。
好的,这是提出问题的代码:
old_values = float((removeprc(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)))
browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)
是一个用于获取网站价值的selenium工具。正如您稍后将看到的,检索到的元素是一个应该与 float() 一起使用的数字
“remove prc”是我创建的一个小函数,用于删除数字的%,如下:
def removeprc(string): #removes the % from a string
string = str(string)
list = string.split('%')
string = " ".join(list)
return string
这可能不是最好的方法,但当我单独测试时它是有效的。
无论如何,这是我运行整个代码时得到的结果
loading page ...
page loaded
acquiring values ...
values acquired
running eth trade
-0.37
Traceback (most recent call last):
File "C:\Users\pc adam\Documents\EISTI\algoprog\perso\python\fichiers\btc\ETHtradingbotV1.py", line 138, in <module>
profit = float(browser.find_element_by_xpath('/html/body/div[3]/section[16]/section[2]/section[2]/section[2]/div/div[1]/table/tbody/tr/td[15]/span').text)
ValueError: could not convert string to float: ''
前5行没用。在第六行,我打印了我想要获取 float() 的内容
的。正如您所看到的,它应该可以工作并且......它确实可以!有时。
这是最奇怪的事情,它有一半的时间运行得很好!
我在互联网上读到,如果您尝试 float() 不是数字的东西或者其中有奇怪的东西(例如空格),就会发生这种情况。正如你所看到的,我认为这里的情况并非如此。
当我尝试通过运行程序的简化版本来隔离问题时,如下所示:
a = "-0.06%"
def removeprc(string): #removes the % from a string
string = str(string)
list = string.split('%')
string = " ".join(list)
return string
b = float(removeprc(a))
print(b)
它输出-0.06并且工作完美???
所以我真的被困在这里了。它应该有效,但事实并非如此。即使最糟糕,它也有效有时, 没原因。当我隔离问题时,它工作得很好。
任何帮助将不胜感激!
哦,如果你想看entire代码,在这里:https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py