【问题标题】:Regex - Match javascript variables in html source code正则表达式 - 匹配 html 源代码中的 javascript 变量
【发布时间】: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


【解决方案1】:

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

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

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2015-07-06
    • 2013-03-14
    • 1970-01-01
    • 2011-12-02
    • 2011-11-29
    • 2012-09-22
    相关资源
    最近更新 更多