Python 从解析列表中平均价格
嗨,我想能够抓住这个网站的价格,解析成整数,然后平均他们。尝试了一些方法,但仍在努力解析出最终的数字Python 从解析列表中平均价格,python,python-3.x,list,beautifulsoup,Python,Python 3.x,List,Beautifulsoup,嗨,我想能够抓住这个网站的价格,解析成整数,然后平均他们。尝试了一些方法,但仍在努力解析出最终的数字 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_
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
有没有办法将他们平均化?对不起,伙计们,谢谢 下面是一个类似的例子。如果你愿意的话,你可以做得更精简一些,但这会给你一个列表中数字的平均值 编辑:将您的欧元符号替换为美元符号 要将字符串转换为int,只需使用int(string)
以下解决方案读取测试列表,然后使用自定义函数
convert\u 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.33333333 4
…努力解析出最终的数字
-您的意思是无法从汤中提取所需的数据
?你要做的就是打印价格
,难道你不应该把它转换成浮点数,放在一个容器中,对容器中的值求和,然后除以吗?你应该提供一个页面的最小示例。内容
-。我打印只是为了查看发生了什么。我正在努力转换另一个:我现在有945087508450-我怎么能把它们分开?总和(价格)/len(价格)int('8450')
产生一个值错误。啊,你是欧元货币符号。我在Python中使用了字符串替换方法。在第二个例子中。我想这是你想要的工作,但不是在我的forloop中,因为它一次只做一个。有没有一种方法可以将我所有的单独循环输出返回到一个完整的列表中,就像您的“测试”列表一样?
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)