2013-06-28 6 views
1

re 모듈을 사용하여 모든 attrs를 포함하여 문자열에서 모든 HTML 노드를 추출합니다. 그러나 각 attr을 하나의 그룹으로 만들려면 matchobj.group()을 사용하면됩니다. 노드의 attrs 수는 유연합니다. 이것은 내가 혼란스러워하는 곳입니다. 나는 그런 정규식을 쓰는 방법을 모른다. </?(\w+)(\s\w+[^>]*?)*/?>'을 시도했지만 과 같은 노드의 경우 두 그룹에만 [('a'), ('style="bbb")]을 부여 할 수 있습니다.
좋은 HTML 파서가 있다는 것을 알고 있습니다. 그러나 실제로 저는 attrs의 값을 추출하지 않을 것입니다. 원시 문자열을 수정해야합니다.regex를 사용하여 모든 HTML attrs 추출

+1

FFS ... http://www.crummy.com/software/BeautifulSoup/ –

+0

HTML 파서 대신 정규식의 사용을 고려 . http://www.crummy.com/software/BeautifulSoup/ – Achrome

+0

정상적인 첫 번째 경기는 두 번째 경기가 덮어 씁니다. –

답변

1

설명

은 속성의 무한한 수를 캡처하려면 :

>>> from bs4 import BeautifulSoup as BS 
>>> html = """<a href='aaa' style='bbb'>""" 
>>> soup = BS(html) 
>>> mytag = soup.find('a') 
>>> print mytag['href'] 
aaa 
>>> print mytag['style'] 
bbb 

을 아니면 사전을 원하는 경우 : BeautifulSoup 사용 전체 요소. 그런 다음 요소를 반복하고 일치하는 속성의 배열을 가져옵니다.

정규식은 모든 요소를 ​​잡아합니다 :

작업을 참조하십시오 \s\w+=(?:'[^']*'|"[^"]*"|[^'"][^\s>]*)(?=\s|>)

enter image description here

파이썬 예 : <\w+(?=\s|>)(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?>

enter image description here

정규식 하나의 요소에서 모든 속성을 잡아 예 : http://repl.it/J0t/4

코드

import re 

string = """ 
<a href="i.like.kittens.com" NotRealAttribute=' true="4>2"' class=Fonzie>text</a> 
"""; 

for matchElementObj in re.finditer(r'<\w+(?=\s|>)(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*?>', string, re.M|re.I|re.S): 
    print "-------" 
    print "matchElementObj.group(0) : ", matchElementObj.group(0) 

    for matchAttributesObj in re.finditer(r'\s\w+=(?:\'[^\']*\'|"[^"]*"|[^\'"][^\s>]*)(?=\s|>)', string, re.M|re.I|re.S): 
     print "matchAttributesObj.group(0) : ", matchAttributesObj.group(0) 

출력

------- 
matchElementObj.group(0) : <a href="i.like.kittens.com" NotRealAttribute=' true="4>2"' class=Fonzie> 
matchAttributesObj.group(0) : href="i.like.kittens.com" 
matchAttributesObj.group(0) : NotRealAttribute=' true="4>2"' 
matchAttributesObj.group(0) : class=Fonzie 

3

Please don't use regex. 그것은 당신이 당겨 처음 두 단계 과정을 할 필요가

>>> print mytag.attrs 
{'style': 'bbb', 'href': 'aaa'} 
+0

나는 HTML 파서가 좋은 선택이어야하지만 실제로는 그들이 나를 위해 일할 수 있다고 생각하지 않는다. 원시 문자열을 수정해야합니다. – zhangyangyu

+0

@zhangyangyu [this] (http://www.crummy.com/software/BeautifulSoup/bs4/doc/#replace-with)를보십시오 – TerryA

+0

downvoter가 downvoted 이유를 명확히 할 수 있습니까? – TerryA

관련 문제