【发布时间】: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