【问题标题】:python beautifulsoup .text None Typepython beautifulsoup .text 无 类型
【发布时间】:2017-10-14 00:11:24
【问题描述】:

我正在用 Beautiful Soup 抓取一个网站。我正在寻找表格中的“prtype”文本。我的问题是,这个专栏并不总是存在的。

如果该列存在,则以下代码可以正常工作:

prtyp = soup.find("dd", attrs={"class":"is_type g"}).text.strip()

但是,如果没有这个类的列,我会收到以下错误:

'NoneType' object has no attribute 'text'

这是我试图摆脱这个问题的尝试之一,但是 prtyp 是一个 str 并且我取回了整个 html 标签,或者 .text 不起作用。当然。

prtyp = soup.find("dd", attrs={"class":"is_type g"})
if prtyp is None:
    prtyp = "no type"
else:
    whgtyp.text.strip()
    print("prtype:", prtype)

【问题讨论】:

  • try: whgtyp.text.strip() print("prtype:", prtype); except AttributeError: prtyp = "no type"

标签: python if-statement text beautifulsoup nonetype


【解决方案1】:

如果您想提取该字符串,可以执行以下操作

if "prtype" in soup.find("body").text:
    prtyp = soup.find("dd", attrs={"class":"is_type g"})
    if prtyp is None:
       prtyp = "no type"
    else:
       # whgtyp.text.strip() # I don't know what it does
       print("prtype:", prtype)

您可以检查字符串是否存在于 HTML 正文中,无论如何我看到在您的 find 方法中您正在寻找“dd”标签,如果您想在表格中搜索,它应该在 td 标签中(如果是 HTML 表格)

【讨论】:

    【解决方案2】:

    感谢您的回答。还没试过,但找到了一个答案:

    prtyp = soup.find("dd", attrs={"class":"is_type g"}).text.strip() if soup.find("dd", attrs={"class":"is_type g"}) else "no type"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 2018-07-16
      • 2019-06-04
      • 2014-02-28
      相关资源
      最近更新 更多