多目的ソリューション:
image_re = re.compile(r"""
(?P<img_tag><img)\s+ #tag starts
[^>]*? #other attributes
src= #start of src attribute
(?P<quote>["''])? #optional open quote
(?P<image>[^"'>]+) #image file name
(?(quote)(?P=quote)) #close quote
[^>]*? #other attributes
> #end of tag
""", re.IGNORECASE|re.VERBOSE) #re.VERBOSE allows to define regex in readable format with comments
image_tags = []
for match in image_re.finditer(content):
image_tags.append(match.group("img_tag"))
#print found image_tags
for image_tag in image_tags:
print image_tag
正規表現の定義でわかるように、含まれています
(?P<group_name>regex)
見つかったグループに、番号ではなく でアクセスできますgroup_name
。読みやすさのためです。したがって、タグのすべてのsrc
属性を表示したい場合は、次のように記述します。img
for match in image_re.finditer(content):
image_tags.append(match.group("image"))
この image_tags リストの後、イメージ タグの src が含まれます。
また、html を解析する必要がある場合、まさにその目的のために設計されたインストゥルメントがあります。たとえば、 xpath式を使用するのはlxmlです。