2015-05-27 87 views
7

如何從HTML頁面獲取輸入值如何通過使用python獲取隱藏的輸入值?

<input type="hidden" name="captId" value="AqXpRsh3s9QHfxUb6r4b7uOWqMT" ng-model="captId"> 

我輸入名字[NAME = 「captId」],需要他的價值

import re , urllib , urllib2 
a = urllib2.urlopen('http://www.example.com/','').read() 

感謝名單


更新1

我安裝BeautifulSoup和使用它,但存在一些錯誤

代碼

import re , urllib , urllib2 
a = urllib2.urlopen('http://www.example.com/','').read() 
soup = BeautifulSoup(a) 
value = soup.find('input', {'name': 'scnt'}).get('value') 

錯誤

「湯= BeautifulSoup的(a) NameError:名稱 'BeautifulSoup' 沒有定義」

+2

你得到一個隱藏的輸入值相同的方式,你得到任何其他輸入:

例如假設txt包含整個頁面,找到所有隱藏的字段是一樣簡單。 – Barmar

+0

是的,但我用什麼re.findall或re.search和如何寫真模式 – IBRA

+0

BeautifulSoup應該是你需要的:你首先選擇表單,然後隱藏的領域。 –

回答

4

使用re模塊來解析xml或html通常被認爲是不好的做法。只有在對您嘗試解析的頁面有反應時才使用它。如果不是,您的正則表達式非常複雜,或者如果某人用替換<input name="..." type="hidden" .../>或幾乎其他任何東西,腳本可能會中斷。

BeautifulSoup是一個HTML解析器:

  • 自動修復小錯誤(未關閉標籤...)
  • 建立一個DOM樹
  • 允許您瀏覽該樹,搜索特定的標籤,具有特定屬性的
  • 是可用使用Python 2和3

除非你有很好的理由ñ不要這樣做,你應該使用它而不是re進行HTML解析。

from bs4 import BeautifulSoup 
soup = BeautifulSoup(txt) 
hidden_tags = soup.find_all("input", type="hidden") 
for tag in hidden_tags: 
    # tag.name is the name and tag.value the value, simple isn't it ? 
+0

感謝bro 你能給我舉一個例子來使用BeautifulSoup – IBRA

+0

@IBRA有很多被引用的位置...但請參閱我的編輯 –

+0

我更新了這個問題 – IBRA

相關問題