是否有做以下更簡潔/正確的/ Python的方式:Python化的方式找到一個正則表達式匹配
url = "http://0.0.0.0:3000/authenticate/login"
re_token = re.compile("<[^>]*authenticity_token[^>]*value=\"([^\"]*)")
for line in urllib2.urlopen(url):
if re_token.match(line):
token = re_token.findall(line)[0]
break
我想從一個HTML名爲「authenticity_token」的輸入標籤的價值頁面:
<input name="authenticity_token" type="hidden" value="WTumSWohmrxcoiDtgpPRcxUMh/D9m7O7T6HOhWH+Yw4=" />
正確的做法是使用BeautifulSoup這樣的HTML解析器:http://www.crummy.com/software/BeautifulSoup/。看到這裏的原因:http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with- a-rege – 2009-11-08 23:10:09
正則表達式不應該與html/XML一起使用 - 有太多方法可能導致事情中斷。看看BeautiflSoup或其中一個html解析器模塊。 – 2009-11-08 23:11:13
您需要使用像BeautifulSoup這樣的解析器。如果你使用正則表達式,並且惡意用戶想辦法將一些與正則表達式匹配的文本放在頁面某處,例如,在評論或什麼?你最終以爲這是真正的問題,這是在尋求麻煩。 – 2009-11-09 00:31:16