我是stack overflow上的新手,我正在用python寫一個腳本,我有一個可以解決的問題,我需要用產品的價格創建一個變數,現在我已經收集到了歐元的十進制價格,感謝網路刮獎。
import bs4, requests
link = "https://hookpod.shop/products/hookpod-screw-adapter"/span>
回應 = requests.get(link)
response.raise_for_status()
soup = bs4.BeatifulSoup(response.text, 'html.parster')
span_price = soup.find('span'/span>, class_='product__price')
輸出給我的是:
<span class="product__price" data-product-price=""> €10.00 </span>
我需要獲取金額(€10.00)并將其轉換為int,有沒有人可以幫助我,我真的需要它
uj5u.com熱心網友回復:
將span_price文本轉換為int可以解決這個問題。
比如說:
var int_span_price = int(span_price.text.replace('€'/span>, ''))
uj5u.com熱心網友回復:
查找方法回傳一個Tag物件,你可以通過text屬性訪問其字串。然后,你應該用strip去除它周圍的空隙,并用切片的方式去除金錢符號,例如。鑄成float,最后用int。
from bs4 import BeautifulSoup
html = '<span class="product__price" data-product-price=""> €10.00 </span> '
span_price = BeautifulSoup(html,'lxml') # 你可以改變決議器。
span_price_value = int(float(span_price.text.strip()[1:])
print(span_price_value)
注意:
- 我使用了另一個分析器的位子,沒有什么區別,只是如果你沒有安裝它,一定要改變它(
lxml) 。
- 如果不使用
strip,那么你應該注意字串的片斷,不要超過1 。
uj5u.com熱心網友回復:
我推薦你使用https://pypi.org/project/price-parser/
要安裝它,請運行pip install price-parser
>>> from price_parser import Price
>>> price = Price.fromstring("22,90 €"/span>)
>>>price
價格(金額=十進制('22.90'), 貨幣='€')
>>> price.amount # numeric price amount。
十進制('22.90')
>>> price.currency # currency symbol, as appears in the string。
'€'
>>> price.amount_text # price amount, as appears in the string[/span].
'22,90'。
>>> price.amount_float # price amount as float, not Decimal。
22.9。
uj5u.com熱心網友回復:
使用Beautiful Soup的tag系統來鎖定該資料,并使用soup.getText()將其提取出來。你也可以決議你在那里做的soup.find方法的結果
。uj5u.com熱心網友回復:
。這里有幾個錯別字,所以我寫了完整的代碼。使用regex來獲取你已經得到的歐元價格中的數字。
import bs4, requests
from bs4 import BeautifulSoup
link = "https://hookpod.shop/products/hookpod-screw-adapter"/span>
回應 = requests.get(link)
response.raise_for_status()
soup = bs4.BeautifulSoup(response.text, 'html.parser')
span_price = soup.find('span'/span>, class_='product__price')
import re
result = re.search(r'd ', span_price.text)
result_int = int(result.group())
result_int
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/324465.html
標籤:
下一篇:棱鏡。通過活動結束對話
