您好,我希望能够从此网站获取价格,将其解析为整数,然后平均。尝试了几种方法,但仍在努力解析最终数字。
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
有没有一种方法可以对它们进行平均?抱歉,谢谢!
答案 0 :(得分:0)
下面是一个类似于您的示例。如果愿意,您可以使其更精简,但这应该可以使列表中的数字平均。
编辑:用美元符号替换您的欧元符号。
要将字符串转换为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))
答案 1 :(得分:0)
以下解决方案会读取您的测试列表,然后使用自定义函数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