【问题标题】:Averaging prices from a parsed list [duplicate]解析列表中的平均价格[重复]
【发布时间】:2019-11-12 23:15:51
【问题描述】:

您好,我希望能够从该站点获取价格,将它们解析为整数,然后平均它们。尝试了几种方法,但一直在努力解析出最终数字。

import requests
from bs4 import BeautifulSoup

URL = 'https://www.watchfinder.co.uk/search?q=114060&orderby=AgeNewToOld'

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'}

page = requests.get(URL, headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')


prices = soup.find_all(class_=('prods_price'))
for price in prices:
    price = price.text
    print(price)

这给了我:

£9,450



£8,750



£8,450

有没有办法平均它们?对不起各位,谢谢!

【问题讨论】:

  • ...struggling to parse out the final numbers - 你的意思是你不能从soup 中提取你需要的数据吗?您所做的只是打印price,您不应该将其转换为浮点数,将其放入容器中,将容器中的值相加然后除吗?
  • 您应该提供page.content - minimal reproducible example 的最小示例。
  • 我打印只是为了了解正在发生的事情。我正在努力达到转换的目的
  • 我现在有 9450 8750 8450 - 如何将它们分开?

标签: python python-3.x list beautifulsoup


【解决方案1】:

以下解决方案读取您的测试列表,然后使用自定义函数convert_to_num 求平均值

test = ['£9,450', "£8,750", "£8,450"]

def convert_to_num(my_list):
        total = 0
        count = 0
        for item in my_list:
                item = item.replace("£","").replace(",","")
                total += int(item)
                count += 1

        return total / count

new_avg = convert_to_num(test)
print(new_avg)

返回8883.333333333334

【讨论】:

  • 可以工作,但不能在我的 forloop 中,因为它一次只做一个。有没有办法将我所有的单独循环输出返回到一个完整的列表中,比如你的“测试”列表?
【解决方案2】:

下面是一个类似于您所拥有的示例。如果你愿意,你可以做得更精简,但这应该会给你一个列表中的平均数字。

编辑:将您的欧元符号替换为美元符号。

要将字符串转换为 int 只需使用 int(string)

price = ['$900','$100','$500','$50']


runSum = 0

for i in price:
    convt = i.replace('$', '') 
    numHld = int(convt)
    runSum = runSum + numHld

avg = runSum/len(price)

print(str(avg))

【讨论】:

  • sum(prices)/len(prices)
  • int('£8,450') 产生 ValueError。
  • 啊,你是欧元货币符号。我在 Python 中使用了字符串替换方法。在第二个例子中。我认为这是你想要的
猜你喜欢
  • 2020-05-05
  • 1970-01-01
  • 2017-03-15
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
相关资源
最近更新 更多