python beautifulsoup.text None Typ

2024-10-03 15:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用漂亮的汤刮一个网站。我在一个表中寻找“prtype”文本。我的问题是,这个专栏并不总是存在的。在

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

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

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

^{pr2}$

这是我试图摆脱这个问题的一次尝试,但是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)

Tags: 代码text文本is网站typefindattrs
2条回答

如果你想提取那根绳子,你可以做以下的事

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表)

谢谢你的回答。还没试过,但找到了一个简单的答案:

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

相关问题 更多 >