亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

scrapy:添加一些數學條件

scrapy:添加一些數學條件

回首憶惘然 2023-06-06 15:32:11
使用 python 3.8 和 scrapy 1.6,我想檢查產品的星級是否等于或大于 3.5,然后檢查另一個條件(如果 discount_percent 等于或大于 10%),然后抓取該產品的一些元素。問題是,我猜,scraped star 和 discount_percent 元素是非英文數字并且包含“%”。因此,雖然我使用的是 utf8,但當我將代碼行包裝在 float() 和 int() 函數中時,我得到了這個日志:這是我的蜘蛛代碼:    def parse(self, response):        for product in response.xpath("//ul[@class='c-listing__items']/li"):            title= product.xpath(".//a[@class='js-product-url']/text()").get()            star= float(product.xpath(".//div[@class='c-product-box__engagement-rating']/text()").get())            discounted_percent= int(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get())            discounted_price= int(product.xpath(".//div[@class='c-price__value-wrapper']/text()").get())            original_price= int(product.xpath(".//div[@class='c-price__value c-price__value--plp']/del/text()").get())            url= response.urljoin(product.xpath(".//a[@class='js-product-url']/@href").get())            if star>=3.5 and discounted_percent>=10:                yield{                    'title':title,                    'star':star,                    'discounted_percent':discounted_percent,                    'discounted_price':discounted_price,                    'original_price':original_price,                    'url':url                }       我該如何解決這個問題?感謝您的幫助!
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

問題來自您正在使用的以下幾行int():


discounted_percent= int(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get())

discounted_price= int(product.xpath(".//div[@class='c-price__value-wrapper']/text()").get())

original_price= int(product.xpath(".//div[@class='c-price__value c-price__value--plp']/del/text()").get())

           

但是,您還必須為discounted_priceand執行此original_price操作,確保沒有非數字字符,例如%或 貨幣符號。


這是因為您不能int()在使用非數字字符的字符串上使用,例如int("20%")


一個快速的解決方案是刪除這些字符。在以下情況下discounted_percent:


discounted_percent = int(str(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get().strip()).replace('?', ''))


查看完整回答
反對 回復 2023-06-06
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號