当有标签时找到锚文本

时间:2009-03-02 17:29:44

标签: python regex

我想找到一对< a>之间的文字。链接到给定网站的标签

这是我用来查找内容的重新字符串:

r'''(<a([^<>]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^<>]*)>([^<]*))</a>''' % our_url

结果将是这样的:

r'''(<a([^<>]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^<>]*)>([^<]*))</a>'''

这对于大多数链接来说都很棒,但是在其中包含带标记的链接时会出错。我尝试改变正则表达式的最后部分:

([^<]*))</a>'''

为:

(.*))</a>'''

但是这个链接之后的页面上只有一切,我不想要。我有什么建议可以解决这个问题?

4 个答案:

答案 0 :(得分:3)

而不是:

[^<>]*

尝试:

((?!</a).)*

换句话说,匹配任何不是</a序列开头的字符。

答案 1 :(得分:3)

>>> import re
>>> pattern = re.compile(r'<a.+href=[\'|\"](.+)[\'|\"].*?>(.+)</a>', re.IGNORECASE)
>>> link = '<a href="http://stackoverflow.com/questions/603199/finding-anchor-text-when-there-are-tags-there">Finding anchor text when there are tags there</a>'
>>> re.match(pattern, link).group(1)
'http://stackoverflow.com/questions/603199/finding-anchor-text-when-there-are-tags-there'
>>> re.match(pattern, link).group(2)
'Finding anchor text when there are tags there'

答案 2 :(得分:2)

我不会使用正则表达式 - 使用像Beautiful Soup这样的HTML解析器。

答案 3 :(得分:1)

进行非贪婪的搜索,即

(.*?)
相关问题