簡體   English   中英

美麗的湯,按標簽的內容搜索與標簽

[英]Beautiful Soup, searching by content of tag with tag in it

<th rowspan="3" style="background:#c0cfe4; width:7em">present</th>
<td>ich <a href="/wiki/mache" title="mache">mache</a></td>
<td>wir <strong class="selflink">machen</strong></td>
<th rowspan="3" style="background:#c0cfe4; width:7em">i</th>
<td>ich <a href="/wiki/mache" title="mache">mache</a></td>
<td>wir <strong class="selflink">machen</strong></td>
</tr>
<tr>
<td>du <a href="/wiki/machst" title="machst">machst</a></td>
<td>ihr <a href="/wiki/macht" title="macht">macht</a></td>
<td>du <a href="/wiki/machest" title="machest">machest</a></td>
<td>ihr <a href="/wiki/machet" title="machet">machet</a></td>
</tr>
<th colspan="6" style="background:#9999DF">future i</th>
</tr>
<tr>
<th rowspan="3" style="background:#ccccff">infinitive</th>
<td rowspan="3" colspan="2">machen werden</td>
<th rowspan="3" style="background:#ccccff">subjunctive i</th>
<td>ich werde machen</td>
<td>wir werden machen</td>
</tr>
<tr>
<td>du werdest machen</td>
<td>ihr werdet machen</td>
</tr>
<tr>
<td>er werde machen</td>
<td>sie werden machen</td>
</tr>

我試圖在第9行提取<td>du <a href="/wiki/machst" title="machst">machst</a></td> 。當我使用soup.find_all("td" text="re.compile("^du))進行搜索時soup.find_all("td" text="re.compile("^du))我得到的就是第24行的標簽。這樣做的正確方法是什么?

作為替代方法,您將獲得具有以du開頭的textnext td

print next(td for td in soup.find_all("td") if td.text.startswith('du')) 

此外,您可以將函數傳遞find_all()

def td_with_du(tag):
    return tag.name == 'td' and tag.text.startswith('du')

print soup.find_all(td_with_du)

演示:

>>> from bs4 import BeautifulSoup
>>> data = """
Your HTML code goes here
"""
>>> soup = BeautifulSoup(data)
>>> def td_with_du(tag):
...     return tag.name == 'td' and tag.text.startswith('du')
... 
>>> for td in soup.find_all(td_with_du):
...     print td.text
... 
du machst
du machest
du werdest machen

問題是你無法將標簽與文本和嵌套標簽匹配(請參閱如何從<dt>標簽中獲取帶有<span>的文本? ),這就是為什么你唯一的匹配是<td>du werdest machen</td>

事實證明,當標簽本身包含嵌套標簽時,Tag對象的string屬性為None 但是,正如Martijn Pieters在上面的鏈接中所述, .text 包含所有嵌套標簽中的所有字符串 ,這就是原因

>>> a = soup.find_all('td')[0]
>>> a
<td>ich <a href="/wiki/mache" title="mache">mache</a></td>
>>> print(a.string)
None
>>> print(a.text)
ich mache
>>> b = soup.find_all('td', text=re.compile('^du'))[0]
>>> b
<td>du werdest machen</td>
>>> print(b.string)
du werdest machen
>>> print(b.text)
du werdest machen

對於解決此問題的方法,您可以看到alecxe的答案。

此解決方案假定您不限於對text="re.compile("^du)進行過濾。

雖然有幾行文本以“du”開頭,但數據中只有一行包含href="/wiki/machst" 因此,如果您對href屬性進行過濾,您將獲得“a”標記,如果您使用其中的父標記,您將獲得您所追求的“td”標記:

soup.find(href="/wiki/machst").parent

如果你需要使用find_all ,而不是find

for a in soup.find_all(href="/wiki/machst"):
    print a.parent

如果由於某種原因無法使用此解決方案,那么如果您能夠明確您正在運營的要求和限制將會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM