所以我正在用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=“draggablenavRightResizeable”]/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行是无用的。在第6行,我打印了我想要得到的浮动() 属于正如你所看到的,它应该起作用并且。。。是的!有时候
这是最奇怪的事情,它有一半的时间都能正常工作! 我在网上读到,如果你尝试浮动不是数字的东西,或者里面有奇怪的东西,比如空格,就会发生这种情况。正如你所看到的,我认为情况并非如此
当我试图通过运行简化版本的程序来隔离问题时,如下所示:
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,工作正常
所以我真的被困在这里了。它应该能工作,但不能。甚至最糟糕的是,它有时也会毫无理由地工作。当我隔离问题时,它工作正常
任何帮助都将不胜感激
哦,如果你想看到整个代码,它在这里:https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py
返回的文本是空字符串,因此无法转换为
float
。加支票您已在此处将关键字用作变量。我想这就是为什么有时候它不起作用的原因。 与str()类似,list()是一种将变量转换为列表的方法。我想,试着像下面这样重命名变量
此错误消息
…意味着Python解释器无法将字符串转换为float
你离得够近了text方法将返回一个字符串,并去除
%
,而不是您想要的string.split('%')
例如:
印刷品:
此外,
find_element_by_xpath()
将只标识单个元素,使用文本将得到单个字符串,因此string = " ".join(list)
似乎是多余的因此,要有效地剥离
%
,将字符串转换为浮点并打印,有效的代码行将是:更新
当调用代码行时,DOM中没有呈现包含所需文本的元素,因此仍然会看到错误。作为一种解决方案,您需要为
visibility_of_element_located()
引入WebDriverWait,并且可以使用以下Locator Strategy:注意:您必须添加以下导入:
相关问题 更多 >
编程相关推荐