2008-09-10 1 views
10

HTML의 숨겨진 입력 필드 값을 가져 오려고합니다.HTML 구문 분석을위한 Python 정규 표현식 (BeautifulSoup)

<input type="hidden" name="fooId" value="12-3456789-1111111111" /> 

나는 내가 HTML에서 줄을 알고 주어진 fooId의 값을 반환합니다 파이썬에서 정규 표현식을 작성하려면이

<input type="hidden" name="fooId" value="**[id is here]**" /> 

누군가가 파이썬에서 예를 제공 할 수있는 형식을 따릅니다 값으로 HTML을 파싱하려면?

답변

27

은 BeautifulSoup로는 정규식보다 쓰기 어렵습니다,하지만 ... 난 그냥 당신이 이미 사용할 정규 표현식 알고 주어진 BeautifulSoup로 예제를 기여하고있어 훨씬 더 강력합니다 : -)

내가 Vinko BeautifulSoup에 동의
from BeautifulSoup import BeautifulSoup 

#Or retrieve it from the web, etc. 
html_data = open('/yourwebsite/page.html','r').read() 

#Create the soup object from the HTML data 
soup = BeautifulSoup(html_data) 
fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag 
value = fooId.attrs[2][1] #The value of the third attribute of the desired tag 
          #or index it directly via fooId['value'] 
+0

"새로운"키워드가 불일치라고 생각합니다. –

0
/<input type="hidden" name="fooId" value="([\d-]+)" \/>/ 
5

구문 분석은 정말

와서 가서 년 동안 가장자리 경우 버그를 추격 할 것이다 당신이 그것을 피할 수 있다면 자신의 롤하지 않는 분야 중 하나입니다

BeautifulSoup을 사용하는 것이 좋습니다. 그것은 아주 좋은 평판을 가지고 있으며 사용하기가 매우 쉬운 것처럼 문서에서 보입니다. 이 특별한 경우를 들어

+1

일반적인 경우에 동의하지만 일회성 스크립트를 사용하여 하나 또는 두 개의 매우 구체적인 것을 구문 분석하는 경우 정규식을 사용하면 더 쉽게 사용할 수 있습니다. 분명히 더 깨지기 쉽지만 유지 보수성이 문제가 아니라면 걱정할 필요가 없습니다. 즉, BeautifulSoup는 환상적입니다. –

+0

나는 정규 표현식을 좋아하지만 Orion과 동의해야한다. 이것은 Jamie Zawinski의 유명한 인용문이 떠오르는시기 중 하나입니다. "이제 두 가지 문제가 있습니다." –

8
import re 
reg = re.compile('<input type="hidden" name="([^"]*)" value="<id>" />') 
value = reg.search(inputHTML).group(1) 
print 'Value is', value 
0
/<input\s+type="hidden"\s+name="([A-Za-z0-9_]+)"\s+value="([A-Za-z0-9_\-]*)"\s*/>/ 

>>> import re 
>>> s = '<input type="hidden" name="fooId" value="12-3456789-1111111111" />' 
>>> re.match('<input\s+type="hidden"\s+name="([A-Za-z0-9_]+)"\s+value="([A-Za-z0-9_\-]*)"\s*/>', s).groups() 
('fooId', '12-3456789-1111111111') 
18

길을 가야하는 것입니다. 그러나 나는 세 번째 속성 인 value에 의존하기보다 fooId['value']에서 get the attribute으로 제안합니다.

from BeautifulSoup import BeautifulSoup 
#Or retrieve it from the web, etc. 
html_data = open('/yourwebsite/page.html','r').read() 
#Create the soup object from the HTML data 
soup = BeautifulSoup(html_data) 
fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag 
value = fooId['value'] #The value attribute 
+0

'new'? 파이썬이 아니에요! – habnabit

1

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이 이러한 예측할 수없는 변형과 일치 할뿐만 아니라 개별 태그 속성 및 해당 값을 읽기 쉽게하는 객체의 데이터를 반환한다는 것을 알 수 있습니다.