如何根据python中的条件提取文本

我有如下的汤数据。


<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>


我需要这些标签中的文本数据a,也许href=/title/*wildcharacter*


我的可能看起来像这样。


titles = []


for a in soup.find_all("a",href=True):

    if a.text:

        titles.append(a.text.replace('\n'," "))

print(titles)

但是在这种情况下,我会从所有a标签中获取文本。我只需href要有"/title/***".


慕尼黑8549860
浏览 80回答 3
3回答

守着一只汪

我猜你想要这样:from bs4 import BeautifulSouphtml = '''<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):&nbsp; &nbsp; if a.text:&nbsp; &nbsp; &nbsp; &nbsp; titles.append(a.text.replace('\n'," "))print(titles)输出:[' Pulp Fiction ', ' Fight Club ']

三国纷争

您可以使用正则表达式来搜索属性的内容(在本例中为 href)。

慕哥9229398

1.) 要获取所有以 开头的<a>标签,您可以使用 CSS 选择器。href="/title/"a[href^="/title/"]2.) 要去除标签内的所有文本,您可以使用.get_text()with 参数strip=Truesoup = 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']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python