2017-10-14 73 views
0

我正在刮美丽的汤的网站。我正在查找表中的“prtype”文本。我的问题是,这个专栏并不总是存在。python beautifulsoup .text无类型

如果列存在以下代码工作正常:

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) 
+0

'尝试:whgtyp.text.strip() 打印( “prtype:” prtype); AttributeError除外:prtyp =“no type”' – davedwards

回答

0

如果你想提取字符串中,你可以做跟随

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体存在的字符串,反正我看到,在您的查找方法,你正在寻找一个“dd”标签,如果你想在一个表中搜索,它应该在一个td标签(如果它是一个HTML表)

0

谢谢你的答案。没有尝试它然而却发现一个行回答:

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