python使用正则提取指定的值并添加到字典
巴扎黑
巴扎黑 2017-04-18 10:13:17
[Python讨论组]
巴扎黑
巴扎黑

全部回复(4)
PHP中文网

参考代码,BeautifulSoup的用法可以阅读官方文档

html = '<input class="input-xlarge focused" id="listCode" name="listCode" readonly="true" type="text" value="001"></input><input class="input-xlarge focused" id="type" name="type" readonly="true" type="text" value="002"></input><input class="input-xlarge focused" id="yyc" name="yyc" readonly="true" type="text" value="yyzz"></input>'
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "lxml")
content = dict()
datas = soup.find_all("input", class_="input-xlarge focused")
for data in datas:
    content[data["name"]] = data["value"]

print(content)
高洛峰

re方法

txt = "内容"
import re
inputTxt = re.compile(r'<input.*?</input>', re.S)
nameTxt = re.compile(r'name="(.*?)"')
valueTxt = re.compile(r'value="(.*?)"')

content = {}

for i in re.findall(inputTxt, txt):
    content[re.findall(nameTxt,i)[0]] = re.findall(valueTxt, i)[0]

print(content)
高洛峰

同样功能用HTMLParser实现了一下:

from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint

class MyHTMLParser(HTMLParser):

    def __init__(self):
        self.input_tag_d = {}
        HTMLParser.__init__(self)
        # super(MyHTMLParser, self).__init__()

    def handle_starttag(self, tag, attrs):
        if tag != 'input':
            return
        for attr in attrs:
            if attr[0] == 'name':
                self.input_tag_d[attr[1]] = ''
        for attr in attrs:
            if attr[0] == 'name':
                name = attr[1]
            if attr[0] == 'value' :
                self.input_tag_d[name] = attr[1]

parser = MyHTMLParser()
html_str = '''<input class="input-xlarge focused" id="listCode" name="listCode" readonly="true" type="text" value="001">
</input>
<input class="input-xlarge focused" id="type" name="type" readonly="true" type="text" value="002">
</input>
<input class="input-xlarge focused" id="yyc" name="yyc" readonly="true" type="text" value="yyzz">
</input>'''
parser.feed(html_str)
print(parser.input_tag_d)

>>> {'type': '002', 'yyc': 'yyzz', 'listCode': '001'}
阿神

只用自带re模块不是更容易实现?

s = '''<input class="input-xlarge focused" id="listCode" name="listCode" readonly="true" type="text" value="001">
</input>
<input class="input-xlarge focused" id="type" name="type" readonly="true" type="text" value="002">
</input>
<input class="input-xlarge focused" id="yyc" name="yyc" readonly="true" type="text" value="yyzz">
</input>'''

import re
compile = r'name="(\S+)".*value="(\S+)"'
matches  = re.finditer(compile,s)
result = dict()
for match in matches:
    result[match.group(1)] = match.group(2)
    
print(result)    


{'yyc': 'yyzz', 'type': '002', 'listCode': '001'}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号