2017-09-23 12 views
0

私はAmazonを掻き集めようとしていて、ページ内のアイテムの価格を取得しようとしていましたが、Amazonページのすべてのアイテムが価格を持っているわけではありません時にはそれが終わりなし.findがnoneに等しい場合のデフォルト値を与える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) 

に私もこの

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 
のようなforループを持つsingle_Dataの価格を実行するために使用

AttributeError: 'NoneType' object has no attribute 'string' 

エラーに等しい消すことができます210

は、どのように私はそれがどの

("span", {"id": "priceblock_ourprice"}) 

を見つけることができなかった場合、それは私が好きたいエラーを与えるか「なし」を書かないために持っていますが、代わりに文字列値price_in変数を与えないことを設定することができます。 "現在このアイテムには価格はありません"。あなたのエラーメッセージに注目

おかげXX

答えて

0

は、我々は、アイテムが価格、ITEM_PRICE ==なしを持っていないときにことがわかります。したがって、あなたはそれがNoneの場合、「price_in = item_price.string」上記の文がチェックする場合は追加して、その代わりに=「いくつかのフレーズ」Pythonのマントラの

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

ありがとうございました!私は 'None' ahahと書いていました、それを感謝します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 

一つをprice_in設定した場合、許可よりも許しを求めるのは簡単だということです。文字列を抽出し、文字列を取得できない場合は戻り値をデフォルト値に戻してください。

関連する問題