2017-05-25 73 views
0

我解析一些XML與BeautifulSoup,並有看起來像數據登記爲真。所以我有:布爾不是字符串等價

for e in soup.findAll('title'): 
    if e == '<title>main title</title>': 
     pass 
    else: 
     print (e) 

這仍然返回所有標題,包括main title。我試過刪除標題標籤。

感謝您的任何幫助。

回答

2

您布爾不能正常工作,它將永遠是假的。你可以將它轉換爲字符串然後比較它們。

試試這個:

for e in soup.find_all("title"): 
    if str(e) == '<title>main title</title>': 
     pass 
    else: 
     print (e) 

輸出:

<title>other title</title> 
<title>another title</title> 
0

您可以檢查節點的文本屬性,而不是節點本身。

from bs4 import BeautifulSoup 
soup = BeautifulSoup("""<title>main title</title> 
<title>other title</title> 
<title>another title</title>""", "html.parser") 

for e in soup.find_all("title"): 
    if e.text != 'main title': 
     print(e) 

#<title>other title</title> 
#<title>another title</title> 
2

如果你想跳過第一個冠軍,然後更好的解決方案是切片名單:

>>> soup.findAll('title')[1:] 
[<title>other title</title>, <title>another title</title>] 
只要你想一個對象 <class 'bs4.element.Tag'>比較字符串