一些正则表达式或什么是在python中提取html标签的“值”的最佳方法?

问题描述 投票:0回答:3

我有一个字符串,其中包含几个html tags与此形式:

string= '<input type="hidden" name="csrf" value="7629b234d1cc2f2a5383f5e6d7dc6bd2">'

我想提取"value",我会用.split做,但我不确定它是否是最好的方式。

输出所需:

7629b234d1cc2f2a5383f5e6d7dc6bd2

任何想法或更好的方式?

python
3个回答
3
投票

你可以使用html.parser

from html.parser import HTMLParser

class ValueFinder(HTMLParser):
    def handle_starttag(self, tag, attrs):
        for attr in attrs:
            if attr[0] == "value":
                print(attr[1])

parser = ValueFinder()
parser.feed('<input type="hidden" name="csrf" value="7629b234d1cc2f2a5383f5e6d7dc6bd2">')

0
投票

你可以使用re.search

import re
string= '<input type="hidden" name="csrf" value="7629b234d1cc2f2a5383f5e6d7dc6bd2">'
m = re.search('value="(.+)?"',string)[1]
print(m)

输出:

629b234d1cc2f2a5383f5e6d7dc6bd2

0
投票

使用正则表达式

import re

match = re.compile(r'(value=\"(.*)\"\>)$').finditer(string)

for i in  match:
    print(i.group(2))

输出:

7629b234d1cc2f2a5383f5e6d7dc6bd2
© www.soinside.com 2019 - 2024. All rights reserved.