Skip to main content
 首页 » 编程设计

python正则表达式在a>元素处拆分字符串并提取链接+文本

2025年05月04日15虾米姐

假设我有几个 <a>字符串中的元素:

s = 'Hello world. <a href="https://stackoverflow.com/">StackOverflow</a> is a great website. <a href="https://www.espn.com/">ESPN</a> is another great website.' 

目标是拆分字符串,以便我得到类似于下面的列表:

l = [ 
    "Hello world. ", 
    {"link": "https://stackoverflow.com/", "title": "StackOverflow"}, 
    " is a great website. ", 
    {"link": "https://www.espn.com/", "title": "ESPN"}, 
    " is another great website.", 
] 

字典可以是我可以从中提取链接和标题的任何对象。有没有我可以用来完成这个的正则表达式?或者有更好的方法吗?

请您参考如下方法:

BeautifulSoup 是比正则表达式更好的工具来解析这个字符串。作为一般规则,不要使用正则表达式来解析 HTML:

s = 'Hello world. <a href="https://stackoverflow.com/">StackOverflow</a> is a great website. <a href="https://www.espn.com/">ESPN</a> is another great website.' 
 
from bs4 import BeautifulSoup, Tag, NavigableString 
 
soup = BeautifulSoup(s, 'html.parser') 
 
out = [] 
 
for c in soup.contents: 
    if isinstance(c, NavigableString): 
        out += [c] 
    elif isinstance(c, Tag) and c.name == 'a' and 'href' in c.attrs: 
        out += [{"link": c['href'], "title": c.text}] 
 
from pprint import pprint 
pprint(out) 

打印:

['Hello world. ', 
 {'link': 'https://stackoverflow.com/', 'title': 'StackOverflow'}, 
 ' is a great website. ', 
 {'link': 'https://www.espn.com/', 'title': 'ESPN'}, 
 ' is another great website.']