【发布时间】:2017-02-16 19:34:57
【问题描述】:
我在几次迭代后被卡住了,无法弄清楚我在这里做错了什么,但我认为它与我正在查看的变量类型有关。
我正在从一个站点解析一些 html:
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
当我评估 no_product 的价值时,我发现:
print no_product
#No Product
print type(no_product)
#<type 'unicode'>
当我现在尝试评估 if 语句时,这行不通:
if no_product == 'No Product':
print 'Success'
else:
print 'Failure'
此 if 子句始终返回“失败”。我试图用
将 no_product 变量编码为字符串no_product = no_product.encode('ascii','ignore')
if 语句仍然会返回 'Failure'。
我正在运行 Python 2.7.10。
【问题讨论】:
-
print repr(no_product)输出什么? -
u'\n无产品\n'
-
正如汤姆所说,只需添加 u。我不像他那样确定你需要换行符。
标签: python if-statement unicode beautifulsoup