在代碼中,我嘗試從網站獲取價格資料。該網站在價格中使用了一個空格,并且浮點類引發了一個標志:無法將字串轉換為浮點數:'1\xa0364' 此代碼應該從網站中提取價格,但是來自網站資訊的價格中的空格會導致一個錯誤。我不確定代碼是否有效,但它不會進一步研究其他功能。
這實際上是價格:1364,但它給出:1\xa0364'
請看代碼:
URL = 'https://www.reebok.se/zig-kinetica-ii-edge-gore-tex/H05172.html'
headers={"user-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0'}
def check_price():
page = requests.get(URL , headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
title = soup.find( class_ = 'gl-heading gl-heading--regular gl-heading--italic name___1EbZs').get_text()
print(title)
price=soup.find( class_ ='gl-price-item gl-price-item--sale notranslate').get_text()
converted_price= float(price[0:5])
uj5u.com熱心網友回復:
如果你只想洗掉空格,你可以這樣做
split join
>>> ''.join("1\xa0364".split())
'1364'
regex replace
>>> import re
>>> re.sub("\s", "", "1\xa0364")
'1364'
您也可能會發現這個答案很有幫助,它基本上從字串中提取數字和小數點并忽略其他所有內容: Python Remove Comma In Dollar Amount 雖然有時它可能會給出一些誤報,例如
>>> other_option("Error: 404 file not found. Try again in 10 seconds")
404.10
uj5u.com熱心網友回復:
你可以使用 replace 來處理這種事情,你的代碼應該是這樣的:
price_str = "1\xa0364"
if len(price_str) >= 4 : # removing white space just for values with 4 or more chars
price = float(price_str.replace(u'\xa0', u''))
else:
price = float(price_str)
uj5u.com熱心網友回復:
您還可以使用正則運算式從已經格式化的腳本標簽中提取,以便使用“。”輕松進行浮點轉換。
import requests, re
URL = 'https://www.reebok.se/zig-kinetica-ii-edge-gore-tex/H05172.html'
HEADERS ={"user-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0'}
def check_price():
page = requests.get(URL , headers=HEADERS)
name, price = [re.search(f'(?<!Brand",)"{i}":"?(.*?)[",]', page.text).group(1) for i in ['name', 'price']]
print(f'{name}: {float(price)}')
check_price()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454724.html
標籤:Python python-3.x 网页抓取 精确
