使用 beautifulsoup 可以執行以下操作:
for heading in soup.find_all('h1'):
print(heading.text)
Top Rated Movies
但是,有沒有一種方法可以在給定文本的情況下自行提取標簽?從上面的示例向后作業的一種方式,例如:
soup.find_tag('Top Rated Movies')
h1
uj5u.com熱心網友回復:
有很多方法。
如果您知道確切的文本,則可以使用text或string爭論
tags = soup.find_all(True, string="Top Rated Movies")
有關使用string引數的更多方法,例如當您只知道部分文本時,您可以查看檔案的相關部分。
此外,對于部分文本,您可以使用lambda
tags = soup.find_all(lambda x: x.name and x.text and 'Top Rated Movies' in x.text)
或者,使用select和-soup-contains選擇器
tags = soup.select(':-soup-contains("Top Rated Movies")')
當然,使用部分匹配方法,您最終也會獲得父標簽,但您可以將它們過濾掉
tags = [t for t in tags if not [p for p in t.parents if p in tags]]
或者,如果您確定目標標簽中沒有嵌套更多標簽,
tags = [t for t in tags if t.find() is None]
不過,在這種情況下,您可以使用:-soup-contains-own選擇器而不需要過濾。
(請注意,您可能需要將html5lib 決議器用于偽類,例如-soup-contains.)
如果您特別想要標簽名稱,請按照上述任何一項操作:
for t in tags: print(t.name)
uj5u.com熱心網友回復:
for tag in soup.findAll(True, text="Top Rated Movies"):
print(tag.name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/525874.html
