问题描述
我正在尝试使用 regex 从网页中提取超链接. Python.
I'm trying to extract the hyperlinks from a webpage using regex in Python.
假设我的文本字符串是:
suppose my text string is:
text = '<a href="/status/ALL">ALL</a></td>/n<a href="/status/ASSIGN">ASSIGN</a></td>'
,我想提取ALL和ASSIGN,我正在使用以下正则表达式:
and I want to extract ALL and ASSIGN,I'm using this regular expression:
re.findall(r'<a href=.*>(\w+)</a>', text, re.DOTALL)
这仅返回ASSIGN.
this just returns ASSIGN.
有人可以帮助我指出正则表达式中的错误吗?我真的是这个话题的新手.
Can someone please help me in pointing out the mistake in the regular expression? I'm really new to this topic.
推荐答案
您正在使用正则表达式,并且将具有此类表达式的XML匹配为.
You are using a regular expression, and matching XML with such expressions get too complicated, too fast.
请不要让自己烦恼,而要使用HTML解析器,Python有多种选择:
Please don't make it hard on yourself and use a HTML parser instead, Python has several to choose from:
- ElementTree 是标准库的一部分
- BeautifulSoup 是一个受欢迎的第三方图书馆
- lxml 是一个快速且功能丰富的基于C的库.
- ElementTree is part of the standard library
- BeautifulSoup is a popular 3rd party library
- lxml is a fast and feature-rich C-based library.
ElementTree示例:
ElementTree example:
from xml.etree import ElementTree
tree = ElementTree.parse('filename.html')
for elem in tree.findall('a'):
print ElementTree.tostring(elem)
这篇关于在python中使用正则表达式从锚标记中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!