2017-06-20 2 views
1
import re 
from bs4 import BeautifulSoup 

>>>html_text = '<li>Location:<a href="tweetLocation">tweetLocation</a></li>' 
>>>soup = BeautifulSoup(html_text) 
>>>print soup.find('li', text=re.compile(r'^Location.*')) 

Ich bekomme Antwort als keine. Kann mir jemand sagen, wie man das findet?BeautifulSoup kann nicht finden Tag li

+0

Mögliches Duplikat [BeautifulSoup - Suche nach Text in einem tag] (https://stackoverflow.com/questions/31958637/ beautifulsoup-search-by-text-inside-a-tag) –

Antwort

1

text Argument (die nun zu string umbenannt wird) prüft tatsächlich ein .string eines Elements die gewünschten Kriterien entsprechen - in diesem Fall ein regulärer Ausdruck ^Location.*.

Nun, es etwas Besonderes über das .string Attribut ist - es Wert ist None wäre, wenn ein Tag mehrere Kinder hat:

Wenn ein Tag mehr als eine Sache enthält, dann ist es nicht klar, welche .String beziehen soll, so wird .String definiert Keine sein

und Ihr li Element tatsächlich mehrere Kinder hat - einen Textknoten Location: und eine a Element. Daher keine Ergebnisse.

Stattdessen suchen Sie das Textelement und dann auf das gewünschte Element erhalten:

In [1]: import re 

In [2]: from bs4 import BeautifulSoup 

In [3]: html_text = '<li>Location:<a href="tweetLocation">tweetLocation</a></li>' 

In [4]: soup = BeautifulSoup(html_text, "html.parser") 

In [5]: soup.find(text=re.compile(r'^Location.*')).find_parent('li') 
Out[5]: <li>Location:<a href="tweetLocation">tweetLocation</a></li> 

In [6]: soup.find(text=re.compile(r'^Location.*')).next_sibling.get_text() 
Out[6]: 'tweetLocation'