2017-10-14 4 views
0

私はBeautiful Soupでウェブサイトを削っています。私はテーブル内の "prtype"テキストを探しています。私の問題は、この列は必ずしも存在しないということです。python beautifulsoup .textなしタイプ

列は次のコードは正常に動作しますが存在する場合:

'NoneType' object has no attribute 'text' 

私の試みの一つであった。このクラスとは列が存在しない場合、私は次のエラーを取得する、

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

しかし、問題を取り除くために、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 = "タイプなし" ' – davedwards

答えて

0

あなたは、その文字列を抽出したい場合は、とにかく、私はあなたのfindメソッドであなたが探していることがわかり、文字列はHTMLのボディに存在するかどうかをチェックすることができます従う

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) 

を行うことができます"dd"タグ、テーブルで検索したい場合は、tdタグ(HTMLテーブルの場合)にあるはずです

0

あなたの答えはありがたいです。まだそれを試してみたが1行答えたdidntは:

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