首页 > 解决方案 > 从一长串中获取所有组

问题描述

我有以下字符串:

aaa<a class="c-item_foot" href="/news/a/">11r11</a></div>bbb<a class="c-item_foot" href="/news/b/">222</a></div>ccgc<a class="c-item_foot" href="/news/c/">3333a333</a></div>ddd<a class="c-item_foot" href="/news/d/">44a444444</a></div>eee

我尝试从这一行获取以下值:

换句话说,要获得 和 之间的<a class="c-item_foot" href="/news/*/"></a></div>。我试图通过以下方式获得它:

text=open("./string.txt","r").read()
print(u'\n'.join(re.findall(r"<a class=\"c-item_foot.*>(.*)</a></div>", text)))

但只能拿到最后一组44a444444。谁能告诉我正确的例子?

标签: pythonregexregex-groupfindall

解决方案


我建议你使用像 BeautifulSoup 这样的 html 解析库。

html_doc = 'aaa<a class="c-item_foot" href="/news/a/">11r11</a></div>bbb<a class="c-item_foot" href="/news/b/">222</a></div>ccgc<a class="c-item_foot" href="/news/c/">3333a333</a></div>ddd<a class="c-item_foot" href="/news/d/">44a444444</a></div>eee'
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
values = [tag.text for tag in soup.find_all('a')]

推荐阅读