jeudi 16 février 2017

If statement comparing variable value extracted from beautifulsoup

I am stuck after several iterations and cannot figure out what I am getting wrong here but I assume that it has sth to do with the variable type I am looking at.

I am parsing some html from a site:

from bs4 import BeautifulSoup
import urllib2
url = 'XXX'

page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, "html.parser")
soup.prettify()

tag = soup.find("div", { "class" : "no-results--header" })
no_product = tag.text

When I assess the value for no_product I find:

print no_product
#"No Product"
print type(no_product)
#<type 'unicode'>

When I now try to evaluate an if statement this does not work out:

if no_product == 'No Product':
  print 'Success'
else:
  print 'Failure'

This if clause always returns 'Failure'. I have tried to encode the no_product variable as string with

no_product = no_product.encode('ascii','ignore')

Still the if statement will return 'Failure'.

I am running Python 2.7.10.

Aucun commentaire:

Enregistrer un commentaire