Pythonic方式找到正则表达式匹配

时间:2009-11-08 22:55:43

标签: regex python

是否有更简洁/正确/ pythonic的方式来执行以下操作:

url = "http://0.0.0.0:3000/authenticate/login"
re_token = re.compile("<[^>]*authenticity_token[^>]*value=\"([^\"]*)")
for line in urllib2.urlopen(url):
    if re_token.match(line):
        token = re_token.findall(line)[0]
        break

我想从HTML页面获取名为“authenticity_token”的输入标记的值:

<input name="authenticity_token" type="hidden" value="WTumSWohmrxcoiDtgpPRcxUMh/D9m7O7T6HOhWH+Yw4=" />

4 个答案:

答案 0 :(得分:6)

您可以使用Beautiful Soup吗?代码基本上看起来像这样:

from BeautifulSoup import BeautifulSoup
url = "hhttp://0.0.0.0:3000/authenticate/login"
page = urlli2b.urlopen(page)
soup = BeautifulSoup(page)
token = soup.find("input", { 'name': 'authenticity_token'})

这样的事情应该有用。我没有对此进行测试,但你可以read the documentation来准确测试。

答案 1 :(得分:1)

您不需要findall调用。而是使用:

m = re_token.match(line)
if m:
    token = m.group(1)
    ....

我认为BeautifulSoup对正则表达式的推荐。

答案 2 :(得分:1)

使用正则表达式没有“pythonic”。如果您不想使用BeautifulSoup(理想情况下应该使用它),只需使用Python出色的字符串操作功能

for line in open("file"):
    line=line.strip()
    if "<input name" in line and "value=" in line:
        item=line.split()
        for i in item:
            if "value" in i:
                print i

输出

$ more file
<input name="authenticity_token" type="hidden" value="WTumSWohmrxcoiDtgpPRcxUMh/D9m7O7T6HOhWH+Yw4=" />
$ python script.py
value="WTumSWohmrxcoiDtgpPRcxUMh/D9m7O7T6HOhWH+Yw4="

答案 3 :(得分:0)

至于为什么不应该使用正则表达式来搜索HTML,主要有两个原因。

第一个是递归定义HTML,而编译成无堆栈状态机的正则表达式不进行递归。你不能编写一个正则表达式,当它遇到一个结束标记时,可以告诉它在它所属的那个标记的路上遇到的开始标记;没有地方可以保存这些信息。

第二个是解析HTML(BeautifulSoup所做的)规范化HTML中允许的各种事物,并且您可能不会在正则表达式中考虑这些事情。要选择一个简单的例子,你要解析的是什么:

<input name="authenticity_token" type="hidden" value="xxx"/>

可以很容易:

<input name='authenticity_token' type="hidden" value="xxx"/>

<input type = "hidden" value = "xxx" name = 'authenticity_token' />

或者我现在没有想到的其他一百种排列中的任何一种。