2008-09-10 12 views
10

HTMLで隠された入力フィールドの値を取得したい。私はHTMLの行がフォーマットPythonの正規表現によるHTML解析(BeautifulSoup)

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

誰かがPythonでの例を提供することができますが、次の知っていることを考えると、私はfooIdの値を返します。Pythonで正規表現を書きたい

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

、値の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

私は一般的なケースでは同意しますが、1つまたは2つの非常に具体的なものを解析するためのスクリプトを実行している場合、正規表現では簡単に使えます。明らかに脆弱ですが、保守性が問題でない場合、それは懸念事項ではありません。つまり、BeautifulSoupは素晴らしいです。 –

+0

私は正規表現が大好きですが、これについてはOrionと同意しなければなりません。これはJamie Zawinskiの有名な引用が心に浮かぶ時の1つです:「今あなたは2つの問題があります」 –

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

は、移動するための方法です。しかし、私は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

「新規」?それはPythonではありません! – habnabit

1

PyparsingはBeautifulSoupと正規表現の中間段階です。 HTMLタグ解析では、大文字と小文字、空白、属性の有無、順序の違いが分かりますが、BSを使うよりも基本タグ抽出の方が簡単なので、正規表現だけではありません。

あなたの探しているものはすべて、開始の "input"タグの属性にあるので、あなたの例は特に簡単です。ここでは正規表現のフィットを与えるだろう、あなたのinputタグにはいくつかのバリエーションを示すpyparsing例があり、また、それはコメント内であれば、タグに一致するようにしない方法を示しています。

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

これらの予期しないバリエーションにピーパルが一致するだけでなく、個々のタグ属性とその値を簡単に読み取ることができるオブジェクト内のデータが返されることがわかります。

関連する問題