如何在python selenium中将文本框数据转换为整数

2024-09-30 14:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力从文本框中获取文本,将其转换为整数,乘以1.2,然后重新插入文本框

我最初得到一个错误,说我不能将其转换为整数(即使字符串刚刚说'2000'),所以我尝试将其转换为浮点,然后将其转换为整数,但现在我得到'ValueError:不能将字符串转换为浮点'

你知道怎么回事吗?我将附加文本框的HTML和python

HTML:

<input id="radius" ng-model="geoCtrl.lineRadius" 
type="text" placeholder="Desired radius from each point of the list" 
maxlength="100" name="targeting[geolocation][radius]" 
ng-class="{'val-ignore': geoCtrl.options !== 'geo'}" 
class="col-lg-12 attr-input ng-pristine ng-valid">

Python:

#code to find radius, multiply it by 1.2, then enter new radius into textbox
browser.find_element_by_id('radius')
first_radius_20percent = browser.find_element_by_id('radius')
current_radius = float(first_radius_20percent.get_attribute('value'))
current_radius = int(first_radius_20percent.get_attribute('value'))
new_radius = int(current_radius*1.2)
first_radius_20percent.clear()
first_radius_20percent.send_keys(new_radius)

Tags: 字符串idnewinputbyhtml整数current
3条回答

根据您共享的HTML:

<input id="radius" ng-model="geoCtrl.lineRadius" type="text" placeholder="Desired radius from each point of the list" maxlength="100" name="targeting[geolocation][radius]" ng-class="{'val-ignore': geoCtrl.options !== 'geo'}" class="col-lg-12 attr-input ng-pristine ng-valid">

我不认为value例如2000,而是认为placeholder是元素中列表中每个点的所需半径。但是,根据您的问题,因为元素是一个Angular元素,所以要提取元素的value,您必须为element_to_be_clickable()诱导WebDriverWait

此外,由于必须将提取的值乘以1.2,因此最好将从get_attribute()返回的值转换为float,但在调用send_keys()时,必须再次转换为string,并使用以下解决方案:

  • 代码块:

    driver.get('https://www.google.com/')
    first_radius_20percent = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "q")))
    # current_float_radius = float(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "radius"))).get_attribute('value'))
    # or
    # current_float_radius = float(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#radius"))).get_attribute('value'))
    current_float_radius = float("2000")
    new_radius = float(current_float_radius*1.2)
    first_radius_20percent.send_keys(str(new_radius))
    

浏览器快照:

float

返回值中可能混合了一些unicode字符,您可以使用encode('ascii', 'ignore')除去它们

current_radius = int(first_radius_20percent.get_attribute('value').encode('ascii', 'ignore'))

因此,解决方案不是数据类型的问题,我的代码在文本框加载后立即提取其值,但“2000”仅在半秒钟左右后才填充。我找到的解决方案是在执行所讨论的python脚本之前添加一个时间延迟

谢谢你的帮助

相关问题 更多 >