2017-09-23 20 views
0

我試圖抓住亞馬遜,試圖獲得頁面中任何項目的價格,事實並非亞馬遜頁面中的所有項目都有價格有時它可以變成它等於無如果.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

回答

0

注意到你的錯誤信息,我們可以看到,當一個項目沒有價格,ITEM_PRICE ==無。所以因此,你只需要添加一個if上面的「price_in = item_price.string」語句來檢查它是否是無,如果是這樣,而不是設置price_in =「一些短語」

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"}): 
     if item_price: 
      price_in = item_price.string 
     else: 
      price_in = "There is currently no price for this item" 
    return price_in 
+0

謝謝!我一直寫'沒有'哈哈,欣賞它xx –

0
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"}): 
    try: 
     price_in = item_price.string 
    except AttributeError: 
     price_in = "price not found" 
return price_in 

一個蟒蛇咒語是否容易要求寬恕而不是允許。嘗試提取字符串,然後如果無法獲取字符串,則將返回值設置爲默認值。

相關問題