pyparsing의 scanString 메서드를 사용하면 실제로 입력 문자열을 얼마나 멀리 통과하는지 더 많이 제어 할 수 있습니다. 귀하의 예에서는 <meta>
태그와 일치하는 표현식을 작성하고 name="description"
태그 만 일치하도록 구문 분석 조치를 추가합니다. 이 코드는 사용자가 변수 htmlsrc
에 페이지의 HTML을 읽고 있다고 가정
이
class MyParser(HTMLParser):
boolean_flag = False
def handle_starttag(self, tag, attrs):
# for example:
self.boolean_flag = (tag == "sometag" and ("id", "someid") in attrs)
def handle_endtag(self, tag):
pass
def handle_data(self, data):
if self.boolean_flag:
raise DataParsedException(data)
class DataParsedException(Exception):
def __init__(self, data):
self.data = data
사용법 :
try:
parser.feed(html.decode())
except DataParsedException as dataParsed:
vars.append(dataParsed.data)
그것은 않습니다
from pyparsing import makeHTMLTags, withAttribute
# makeHTMLTags creates both open and closing tags, only care about the open tag
metaTag = makeHTMLTags("meta")[0]
metaTag.setParseAction(withAttribute(name="description"))
try:
# scanString is a generator that returns each match as it is found
# in the input
tokens,startloc,endloc = metaTag.scanString(htmlsrc).next()
# attributes can be accessed like object attributes if they are
# valid Python names
print tokens.content
# if the attribute name clashes with a Python keyword, or is
# otherwise unsuitable as an identifier, use dict-like access instead
print tokens["content"]
except StopIteration:
print "no matching meta tag found"
파서가 아닌 HTMLParser를 상속 받아야합니까? –
오, HTML을 파싱하기 위해 BeautifulSoup을 사용하는 것이 좋습니다. 사용하기가 훨씬 쉽습니다. –
나는 이것이 오타 일 뿐이라는 결론에 도달하기 쉽다고 생각합니다. 왜냐하면이 코드가 아니라면이 코드는 작동하지 않기 때문입니다. – shylent