如何从元素中获取href标题并删除所有字符串?

时间:2014-10-31 05:35:27

标签: python regex

我需要从网页上获取链接的标题。链接可能看起来像

< a href="http://xxxx">Some text< /a>

< a href="http://xxxx"><div> < image> < /image> < div> < /a>

可能还有其他可以成像的链接,但我最常见的两个就是这两个。我添加了一些空间让页面不把它当作链接。

我需要获得所有some text部分。 msg是网页的代码。我把代码编写为

titleregex=re.compile('<a\s*href="http.*?[\'"].*?>(.+?)</a>')
titles = titleregex.findall(str(msg))

代码优先处理第一类链接但不处理第二类链接。任何人都可以帮我删除所有<xxx>

2 个答案:

答案 0 :(得分:0)

使用此模式

href\s*=\s*\"*[^\">]*

并标记

re.IGNORECASE, re.I  
re.MULTILINE, re.M

参考此 URL 确定可以帮到您

答案 1 :(得分:0)

你需要正确地转义引号。

>>> import re
>>> s = """< a href="http://xxxx"><div> < image> < /image> < div> < /a>
... < a href="http://xxxx">Some text< /a>"""
>>> re.findall(r"< a\s*href=['\"]http.*?['\"][^<>]*>([^<>]*)<\s*/a>", s)
['Some text']

OR

好像你正试图删除所有标签。

>>> s = '< a href="http://xxxx">Some text< /a>'
>>> re.sub(r'<[^<>]*>', r'', s)
'Some text'