2010-08-01 8 views
1

<font color="red">needed-info-here</font> 또는 <span style="font-weight:bold;">needed-info-here</span> 사이에서 임의로 출력하는 웹 사이트에서 정보를 얻어야합니다.파이썬 정규식 도움이 필요합니다

내가

start = '<font color="red">' 
end = '</font>' 
expression = start + '(.*?)' + end 
match = re.compile(expression).search(web_source_code) 
needed_info = match.group(1) 

를 사용할 때 나는 그것을 얻을 수 있지만, 그럼 내가 가져올 선택해야 하나 <font> 또는 <span>, 사이트가 다른 태그를 사용하는 경우, 실패.

언제나 정규 표현식을 수정하여 어떻게 성공할 수 있습니까?

+6

는 "당신이 정규 표현식으로 HTML을 구문 분석하려고 할 때마다, 신성 아이가 처녀의 피를 눈물을 흘린다 :

html = """ need to get info from a website that outputs it between <font color="red">needed-info-here</font> OR <span style="font-weight:bold;">needed-info-here</span>, randomly. <font color="white">but not this info</font> and <span style="font-weight:normal;">dont want this either</span> """ from pyparsing import * font,fontEnd = makeHTMLTags("FONT") # only match <font> tags with color="red" font.setParseAction(withAttribute(color="red")) # only match <span> tags with given style span,spanEnd = makeHTMLTags("SPAN") span.setParseAction(withAttribute(style="font-weight:bold;")) # define full match patterns, define "body" results name for easy access fontpattern = font + SkipTo(fontEnd)("body") + fontEnd spanpattern = span + SkipTo(spanEnd)("body") + spanEnd # now create a single pattern, matching either of the other patterns searchpattern = fontpattern | spanpattern # call searchString, and extract body element from each match for text in searchpattern.searchString(html): print text.body 

인쇄 : 여기

는 질문하여 대한 파싱을 해결하는 방법입니다 러시아어 해커들이 당신의 웹 애플리케이션을 끌어 올렸습니다. " – cji

+3

모두가 html로 re를 사용하지 말라고 말하면 듣는 것이 가장 좋습니다. 새로운 프로젝트로는 다시하지 않을 것입니다. :) 제안 된 솔루션을 지금 사용해보십시오. – anroots

답변

3

당신은 수직 막대와 두 가지 대안에 가입 할 수 있습니다 :

start = '<font color="red">|<span style="font-weight:bold;">' 
end = '</font>|</span>' 

당신이 글꼴 태그는 항상 </span>에 의해 항상 </font>로 span 태그를 폐쇄 할 것을 알고 있기 때문이다.

그러나 HTML을 구문 분석하기 위해 자신의 정규식을 롤링하는 대신 BeautifulSoup와 같은 단색 HTML 파서를 사용하는 것도 고려하십시오. 일반적으로 정규식으로 구문 분석하기에는 적합하지 않습니다.

+0

감사합니다. 작동합니다. – anroots

+0

+1 내 것과는 달리, 실제로 도움이되는 답변 =) – katrielalex

1

정규식은 이 아니지만 HTML 구문 분석을위한 최선의 선택은입니다. 교육을 위해서

, 여기에 귀하의 질문에 대한 가능한 답변입니다 :

start = '<(?P<tag>font|tag) color="red">' 
end = '</(?P=tag)>' 
expression = start + '(.*?)' + end 
이 작업을 끝낼 것
1
expression = '(<font color="red">(.*?)</font>|<span style="font-weight:bold;">(.*?)</span>)' 
match = re.compile(expression).search(web_source_code) 
needed_info = match.group(2) 

하지만 당신은 정말 HTML을

0
을 구문 분석 정규식을 사용하지 않아야

파이썬을 사용하지 않은,하지만 당신은 다음과 동일한 표현을 할 경우, 그것을 작동합니다 :

/(?P<open><(font|span)[^>]*>)(?P<info>[^<]+)(?P<close><\/(font|span)>)/gi 

그러면 "정보"라는 이름으로 필요한 정보에 액세스하십시오.

PS는 -, ... 또한

나는 또한 "정규식 HTML을 구문 분석하지"규칙에 대해 동의하지만, 당신이 글꼴이나 범위 태그 중 하나에 나타납니다 알고 있다면, 그렇게 될 왜 글꼴 태그를 사용합니까? CSS를 배웠던 이후로 글꼴 태그를 사용하지 않았습니다.

1

정규 표현식과 HTML은 그다지 좋지 않습니다. HTML은 정규 표현식을 지나치게 만드는 잠재적 인 변형이 너무 많습니다. BeautifulSoup는 여기에 적용 할 수있는 표준 도구이지만, 특정 이전 태그와 관련하여 특정 태그를 찾으려고 할 때 pyparsing이 효과적 일 수 있으며 때로는 더 간단 할 수도 있습니다.,

needed-info-here 
needed-info-here 
관련 문제