2014-03-13 192 views
0

從網站獲取數據值以便我可以使用它們的最簡單方法是什麼? 因此,我們必須這樣做讓網頁的源數據的簡單方法:Python:從網站提取數據值

usock = urllib2.urlopen("WEBSITE URL") 
data = usock.read() 
usock.close() 
print data 

在我們抓住和打印服務的頁面數據,有兩條線,我們有興趣

<input type="hidden" name="SECRETCODE" value="l53DLeOfj1" /> 
<input type="hidden" name="NotSoSecretCode" value="Nr4MNjyK" /> 

如果我知道我正在尋找哪些值的名稱,那麼獲取值的最佳方法是什麼,以便我可以將它們放入我自己的變量中並進一步與它們一起玩耍?

回答

1

BeautifulSoup將是您最需要的最簡單的解決方案。

html = ''' 
<input type="hidden" name="SECRETCODE" value="l53DLeOfj1" /> 
<input type="hidden" name="NotSoSecretCode" value="Nr4MNjyK" /> 
''' 
soup = BeautifulSoup(html) 
print soup.find("input", {"name":"SECRETCODE"}) 
print soup.find("input", {"name":"NotSoSecretCode"}) 

您可能需要使用正則表達式繁瑣爲了這個目的,以及如果你手上有很多次!

0

如果你可以使用pyparsing然後

from pyparsing import Literal, Suppress, removeQuotes, dblQuotedString 

def cleanQuotedString(name): 
    return dblQuotedString.setParseAction(removeQuotes).setResultsName(name) 

def extractTokens(inputStream): 
    head = Suppress(Literal('<input')) 
    tail = Suppress(Literal('/>')) 
    equalSign = Suppress(Literal('=')) 
    typekey = Suppress(Literal('type')) + equalSign + cleanQuotedString('type') 
    namekey = Suppress(Literal('name')) + equalSign + cleanQuotedString('name') 
    valueKey = Suppress(Literal('value')) + equalSign + cleanQuotedString('value') 

    grammar = head + typekey + namekey + valueKey + tail 

    return grammar.scanString(inputStream) 

usock = urllib2.urlopen("WEBSITE URL") 
tokens = extractTokens(usock.read()) 
usock.close() 
for item, _, _ in tokens: 
    print("Element with type =", item.type, ", name = ", item.name, ", value = ", item.value)