当前位置: 代码迷 >> python >> 正则表达式 - 匹配html源代码中的javascript变量
  详细解决方案

正则表达式 - 匹配html源代码中的javascript变量

热度:69   发布时间:2023-06-13 14:08:03.0

我有一个内置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]

你可以使用这个正则表达式:

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

  相关解决方案