【问题标题】:Is there a way to convert a web element found by selenium into an integer? (Python)有没有办法将 selenium 找到的 web 元素转换为整数? (Python)
【发布时间】:2022-10-23 15:11:32
【问题描述】:
prices = driver.find_elements(By.CLASS_NAME, 'a-price-whole')
for i in range(len(prices)):
    num = float(prices[i].text)
    total_prices.append(num)

我正在尝试将 selenium 在网站上找到的元素转换为整数或 python 中的浮点数,但每次我收到一条错误消息,显示“num = int(prices[i].text) ValueError: invalid literal for int( ) 基数为 10: ''" 或 "num = float(prices[i].text) ValueError: could not convert string to float: ''" 当我尝试将接收到的元素转换为浮点数时。我该如何解决这个问题?

【问题讨论】:

  • 当您使用.text 打印出来时,您得到的所有文本是什么,因为您可能必须将文本输出清理为仅包含数字
  • 事实证明,我在输出中有一堆 None,但是当我尝试过滤掉它们时,只有其中一些在我使用时被过滤:act_prices = [j for j in temp_prices if j is not None] 这让我认为一些输出的 '' 实际上不是 None但我不知道他们是什么...
  • 您想从哪个网站获取这些物品?
  • 我试图从亚马逊那里得到价格。我设法找到了一种方法来避免收集数据中的那些奇怪点,但将有效数据复制到不同的列表中。我只是希望更容易从网站上获取价格,因为我认为那些奇怪的地方可能有我会丢失的数据......
  • 如果你能提供一个我们可能会更好地提供帮助的项目的例子,但由于它目前是写的,很难提供更多额外的建议

标签: python selenium web-scraping type-conversion


【解决方案1】:

在获取价格时,每个文本中都有一个逗号(,),这就是您收到该错误的原因。您必须替换该逗号:

for i in range(len(prices)):
    num = prices[i].text.replace(",","")
    total_prices.append(float(num))

print(total_prices)

【讨论】:

    猜你喜欢
    • 2017-02-14
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2015-04-10
    • 2021-05-15
    • 1970-01-01
    • 2010-10-04
    相关资源
    最近更新 更多