2008-09-10 12 views
10

HTML'de gizli giriş alanının değerini almak istiyorum.Python HTML ayrıştırma için düzenli ifade (BeautifulSoup)

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

Ben HTML hat biliyorum göz önüne alındığında fooId değerini döndürecektir Python normal bir ifade yazmak istiyorum

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

birisi Python bir örnek sağlayabilir biçimine uygundur HTML değeri için ayrıştırmak için?

cevap

27

, BeautifulSoup bir regex daha yazmak için zor, ama ... Ben sadece zaten kullandığınız için hangi regexp'in biliyorum göz önüne alındığında, BeautifulSoup örnekle katkıda ediyorum çok daha sağlamdır: -)

Ben Vinko BeautifulSoup katılıyorum
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

"Yeni" anahtar kelimenin bir uyumsuzluk olduğunu düşünüyorum. –

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

Ayrıştırma Gerçekten

gelip gitmek yıllarca kenar-durumlarda ve hata aşağı peşinde olacağım gibi, bunu önlemek için kendi rulo istemeyen alanlarından biridir

BeautifulSoup'u kullanmanızı öneririz. Çok iyi bir üne sahiptir ve dokümanlardaki kullanımı oldukça kolay gibi görünüyor. Bu özel durumda İçin

+1

Genel bir durum için katılıyorum, ancak bir veya iki çok özel şeyi ayrıştırmak için tek seferlik bir komut dosyası kullanıyorsanız, normal ifadeler hayatı kolaylaştırır. Açıkçası daha kırılgan, ancak eğer sürdürülebilirlik bir sorun değilse, o zaman bir endişe değildir. Yani, BeautifulSoup fantastik. –

+0

Ben regex seviyorum, ama bu konuda Orion ile katılıyorum. Jamie Zawinski'nin ünlü sözlerinin akla geldiği zamanlardan biri budur: "Şimdi iki probleminiz var" –

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

gitmek yoludur. Ancak, üçüncü özellik olan değere güvenmektense fooId['value'] ile get the attribute'u kullanmanızı öneririz.

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

'yeni'? Bu piton değil! – habnabit

1

Pyparsing, BeautifulSoup ve regex arasında iyi bir geçici adımdır. HTML etiket ayrıştırması, durum, boşluk, öznitelik varlığı/yokluğu/düzeni gibi varyasyonları anladığından, bu tür temel etiket çıkartma işlemlerini BS kullanarak yapmaktan daha kolay olduğu için, normal ifadelerden daha sağlamdır.

Örneğiniz, aradığınız her şey açılış "giriş" etiketinin özelliklerinde olduğundan, özellikle basittir. İşte regexes uyuyor verecekti girişinizi etiketi üzerinde çeşitli varyasyonlar gösteren bir pyparsing örnek olduğunu ve aynı zamanda bir yorum içindeki ise bir etiket maç için değil gösterir:

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 

Baskılar:

['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]** 

Püskürtme işleminin yalnızca bu öngörülemeyen varyasyonlarla eşleştiğini değil, veriyi tek tek etiket özelliklerinin ve değerlerinin okunmasını kolaylaştıran bir nesnede döndürdüğünü görebilirsiniz.