2017-02-09 43 views
1

我有一個內部的JavaScript的網頁,我需要匹配2個變量傳遞給函數:正則表達式 - 比賽中的HTML源代碼的JavaScript變量

<html> 
<!--Some html code--> 
document.write(function('variable1', 'variable2')); 
<!--Some html code--> 
</html> 

變量1和變量2,可與混合字符的任意lenght的字串和數字。我需要匹配他們兩個。這是我現在使用:

data = getSoup(url) # my function to get the beautifulsoup object 
script = data.find('script', text = re.compile(r'document\.write\(function\(')).text.replace('document.write(function(\'', '') 
variable1 = script.split("', '")[0] 
variable2 = script.split("', '")[1].replace("'));","") 

但我想用一些更簡單,「安全」(即使因爲不是總是功能是INSITE script標籤

更新: 謝謝到托馬斯·阿尤布答案,我發現了一個簡單的解決方案爲我工作:

script = re.findall(r"document\.write\(function\(\'(.*?)\', \'(.*?)\'\)\)\;", str(data))[0] 
variable1 = script[0] 
variable2 = script[1] 
+0

長話短說,要刪除文件撰寫'(功能( '變量1', '變量2'));''從text'無論變量的名稱? –

+0

無論變量是什麼,我都需要將2個變量提取到2個python變量中。我在想像一個像「document \ .write \(function \('(。*?)','(。*?)'\)\)」的正則表達式;「但我不知道如何匹配2個變量 – Hyperion

+0

像[this](https://ideone.com/oUZxYQ)? –

回答

0

你可以使用這個表達式:

regex = r"document\.write\(function\(\s*'([^']+)'\s*,\s*'([^']+)'\s*\)" 

demo

相關問題