python - How to continue after receiving None response from xml parse -


i finding prices of products amazon using api bottlenose , parsing xml response beautifulsoup. have predefined list of products code iterates through. code:

import bottlenose bn import lxml bs4 import beautifulsoup  = 0 amazon = bn.amazon('myid','mysecretkey','myassoctag',region='uk',maxqps=0.9) list = open('list.txt', 'r')  print "number", "new price:","used price:"  line in list:     = + 1     listclean = line.strip()     response = amazon.itemlookup(itemid=listclean, responsegroup="large")      soup = beautifulsoup(response, "xml")      usedprice=soup.lowestusedprice.amount.string     newprice=soup.lowestnewprice.amount.string     print , newprice, usedprice 

this works fine , run through list of amazon products until gets product doesn't have value set of tags, like no new/used price.

at python throw response:

attributeerror: 'nonetype' object has no attribute 'amount' 

which makes sense there no tags/string found bs searched for. having no value fine i'm trying achieve, code collapses @ point , not continue.

i have tried:

if soup.lowestnewprice.amount != none:     newprice=soup.lowestnewprice.amount.string else:     continue 

and tried:

newprice=0 if soup.lowestnewprice.amount != 0:     newprice=soup.lowestnewprice.amount.string else:     continue 

i @ loss how continue after receiving nonetype value return. unsure whether problem lies fundamentally in language or in libraries i'm using.

you can use exception handling:

try:     # operation causes attributeerror except attributeerror:     continue 

the code in try block executed , if attributeerror raised, execution drop except block (which cause next item in loop ran). if no error raised, code happily skip except block.


if wish set missing values 0 , print, can do

try: newprice=soup.lowestnewprice.amount.string except attributeerror: newprice=0  try: usedprice=soup.lowestusedprice.amount.string except attributeerror: usedprice=0  print , newprice, usedprice 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -