Pyparsing은 BeautifulSoup과 regex 사이의 중간 단계입니다. HTML 태그 파싱은 대/소문자, 공백, 속성 존재/부재/순서의 차이를 이해하지만 BS를 사용하는 것보다 기본 태그 추출의 종류가 더 간단하기 때문에 정규식보다 강력합니다.
찾고있는 모든 것이 여는 "input"태그의 속성에 있으므로 예제가 특히 간단합니다. 여기에 정규 표현식에 맞는을 줄 것입니다 귀하의 의견 태그에 몇 가지 변화를 보여주는 대한 파싱 예이며, 또한 주석 내에있는 경우 태그를 일치하지 않는 방법을 보여줍니다
html = """<html><body>
<input type="hidden" name="fooId" value="**[id is here]**" />
<blah>
<input name="fooId" type="hidden" value="**[id is here too]**" />
<input NAME="fooId" type="hidden" value="**[id is HERE too]**" />
<INPUT NAME="fooId" type="hidden" value="**[and id is even here TOO]**" />
<!--
<input type="hidden" name="fooId" value="**[don't report this id]**" />
-->
<foo>
</body></html>"""
from pyparsing import makeHTMLTags, withAttribute, htmlComment
# use makeHTMLTags to create tag expression - makeHTMLTags returns expressions for
# opening and closing tags, we're only interested in the opening tag
inputTag = makeHTMLTags("input")[0]
# only want input tags with special attributes
inputTag.setParseAction(withAttribute(type="hidden", name="fooId"))
# don't report tags that are commented out
inputTag.ignore(htmlComment)
# use searchString to skip through the input
foundTags = inputTag.searchString(html)
# dump out first result to show all returned tags and attributes
print foundTags[0].dump()
print
# print out the value attribute for all matched tags
for inpTag in foundTags:
print inpTag.value
인쇄 :
['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True]
- empty: True
- name: fooId
- startInput: ['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True]
- empty: True
- name: fooId
- type: hidden
- value: **[id is here]**
- type: hidden
- value: **[id is here]**
**[id is here]**
**[id is here too]**
**[id is HERE too]**
**[and id is even here TOO]**
pyparsing이 이러한 예측할 수없는 변형과 일치 할뿐만 아니라 개별 태그 속성 및 해당 값을 읽기 쉽게하는 객체의 데이터를 반환한다는 것을 알 수 있습니다.
"새로운"키워드가 불일치라고 생각합니다. –