3 回答

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
我猜你想要這樣:
from bs4 import BeautifulSoup
html = '''<a href="/title/tt0110912/" title="Quentin Tarantino">
Pulp Fiction
</a>
<a href="/title/tt0137523/" title="David Fincher">
Fight Club
</a>
<a href="blablabla" title="Yet to Release">
Yet to Release
</a>
<a href="something" title="Movies">
Coming soon
</a>
'''
soup = BeautifulSoup(html, 'html.parser')
titles = []
for a in soup.select('a[href*="/title/"]',href=True):
if a.text:
titles.append(a.text.replace('\n'," "))
print(titles)
輸出:
[' Pulp Fiction ', ' Fight Club ']

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用正則表達(dá)式來(lái)搜索屬性的內(nèi)容(在本例中為 href)。

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
1.) 要獲取所有以 開頭的<a>標(biāo)簽,您可以使用 CSS 選擇器。href="/title/"a[href^="/title/"]
2.) 要去除標(biāo)簽內(nèi)的所有文本,您可以使用.get_text()with 參數(shù)strip=True
soup = BeautifulSoup(html_text, 'html.parser')
out = [a.get_text(strip=True) for a in soup.select('a[href^="/title/"]')]
print(out)
印刷:
['Pulp Fiction', 'Fight Club']
添加回答
舉報(bào)