【发布时间】:2017-06-27 18:17:45
【问题描述】:
我有一个包含 javascript 的网页,我需要匹配传递给函数的 2 个变量:
<html>
<!--Some html code-->
document.write(function('variable1', 'variable2'));
<!--Some html code-->
</html>
variable1 和 variable2 可以是混合字符和数字的任意长度的字符串。我需要匹配他们两个。这是我现在使用的:
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("'));","")
但我想使用更简单和“安全”的东西(即使函数并不总是在脚本标签内。
更新: 感谢 Thomas Ayoub 的回答,我找到了一个适合我的简单解决方案:
script = re.findall(r"document\.write\(function\(\'(.*?)\', \'(.*?)\'\)\)\;", str(data))[0]
variable1 = script[0]
variable2 = script[1]
【问题讨论】:
-
长话短说,无论变量名称如何,您都想从
text中删除document.write(function('variable1', 'variable2'));? -
无论变量是什么,我都需要将 2 个变量提取到 2 个 python 变量中。我在考虑像“document\.write(function('(.*?)', '(.*?)'));”这样的正则表达式但我不知道如何匹配 2 个变量
-
类似this?
-
@ThomasAyoub 是的,它可以工作,但你的代码对我来说太复杂了!我只需要匹配页面上找到的第一组并将变量提取到 python 变量中,例如 var1 = variable1
-
这是better吗?
标签: javascript python regex