當我嘗試運行代碼并將其匯出到 csv 時。出現錯誤“'NoneType' object has no attribute 'text'”,我已經嘗試了各種方法來修復它,但似乎沒有任何效果。ProductName 列印出來,但 Price 是導致錯誤的原因
from bs4 import BeautifulSoup
import requests
import csv
csv_file = open('CultBeauty.csv', 'w', encoding='utf-8')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Product Name','Price'])
for i in range(10):
url = requests.get('https://www.cultbeauty.com/skin-care.list?pageNumber={}&facetFilters=en_beauty_skincareSkinType_content:Dry'.format(i 1)).text
soup = BeautifulSoup(url, 'lxml')
lists = soup.find_all('div', class_= "productBlock")
for list in lists:
ProductName = list.find('h3', class_="productBlock_productName")
ProductName= ProductName.text.strip()
print(ProductName)
Price = list.find('span', {'class' : "productBlock_priceValue"})
Price = Price.text.strip()
print(Price)
csv_writer.writerow([ProductName,Price])
csv_file.close()
output:
Paula's Choice Skin Perfecting 2% BHA Liquid Exfoliant (118ml)
36.00€
Paula's Choice Skin Perfecting 25% AHA and 2% BHA Exfoliant Peel 30ml
44.00€
Sunday Riley GOOD GENES Glycolic Acid Treatment 1.7 fl. oz.
140.00€
BYOMA Hydrating Serum 30ml
14.60€
Elemis Pro-Collagen Cleansing Balm 100g
51.90€
BYOMA Moisturising Gel Cream 50ml
13.50€
Paula's Choice Skin Perfecting 2% BHA Liquid Exfoliant - Trial Size (30ml)
12.00€
etc
but it doesn't save to csv file and brings out the error
uj5u.com熱心網友回復:
某些商品串列可能沒有價格價值。因此您可能會使用try except并且還需要添加user-agent。最好不要使用 list 作為變數,因為 list 是 python 關鍵字。現在它作業順利。
from bs4 import BeautifulSoup
import requests
import csv
csv_file = open('CultBeauty.csv', 'w', encoding='utf-8')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Product Name', 'Price'])
headers={"User-Agent":"mozilla/5.0"}
for i in range(10):
url = requests.get('https://www.cultbeauty.com/skin-care.list?pageNumber={}&facetFilters=en_beauty_skincareSkinType_content:Dry'.format(i 1),headers=headers).text
soup = BeautifulSoup(url, 'lxml')
lists = soup.find_all('div', class_="productBlock")
for lis in lists:
ProductName = lis.find('h3', class_="productBlock_productName")
ProductName = ProductName.text.strip()
print(ProductName)
try:
Price = lis.find('span', {'class': "productBlock_priceValue"})
Price = Price.text.strip()
print(Price)
except:
pass
csv_writer.writerow([ProductName, Price])
csv_file.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471071.html
上一篇:SwiftUI-動態串列、TextField焦點和洗掉
下一篇:下載網頁內容
