我試圖抓住亞馬遜,試圖獲得頁面中任何項目的價格,事實並非亞馬遜頁面中的所有項目都有價格有時它可以變成它等於無如果.find等於無,則給出默認值Python 3
import requests
from bs4 import BeautifulSoup
import itertools
def spider(max_pages):
search = str(input("Search whatever you want and I'll find it on Amazon "))
print("\n")
page = 1
while page <= max_pages:
url = "https://www.amazon.it/s/ref=sr_pg_"+ str(page) + "?rh=n%3A425916031%2Ck%3A" + search + "&page="+ str(page) + "&sort=relevancerank&keywords=" + search
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for link in soup.findAll("a", {"class": "s-access-detail-page"}):
href = link.get("href")
title = link.string
print(title)
print(single_Data(href))
print(href)
page += 1
def single_Data(item_url):
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
priceog= (soup.find("span", {"id": "priceblock_ourprice"}))
price_in = priceog.string
return price_in
spider(1)
在結束時,錯誤
AttributeError: 'NoneType' object has no attribute 'string'
我也用來運行single_Data的價格有一個循環這樣
def single_Data(item_url):
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for item_price in soup.findAll("a", {"class": "a-link-normal"}):
price_in= item_price.string
return price_in
所以,我怎麼能設置,如果它沒有找到任何
("span", {"id": "priceblock_ourprice"})
它沒有給出錯誤信息或寫「無」,而是給price_in的字符串值,我要像變量: 「目前這個項目沒有價格」。
感謝XX
謝謝!我一直寫'沒有'哈哈,欣賞它xx –