我需要从网页上获取链接的标题。链接可能看起来像
< 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>
?
答案 0 :(得分:0)
答案 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'