【问题标题】:If statement comparing variable value extracted from beautifulsoupIf语句比较从beautifulsoup中提取的变量值
【发布时间】: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


【解决方案1】:

如 cmets 中所述,print repr(no_product) 输出 u'\nNo Product\n'。这意味着no_product 的值包括前导换行符和尾随换行符。

为了使比较成功,您需要去掉换行符:

if no_product.strip('\n') == 'No Product':

或更改您要测试的字符串:

if no_product == '\nNo Product\n':

【讨论】:

    【解决方案2】:

    我想说正确的'if'语句应该是:

    if no_product == u'No Product':
    

    u 告诉 Python 它是一个 unicode 字符串。

    不过,我建议您不要使用直接相等,而是使用 in 关键字:

    if 'No Product' in no_product:
    

    这将假定 no_product 不会包含短语“no Product”,除非结果符合您的上述预期。我也喜欢in 构造,因为它消除了隐藏空格造成不匹配的可能性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多