想用beautifulsoup在脚本标签下获得变量值

1 人不认可

我已经从我的HTML源中提取了scrip标签。但我想从标签中获取变量值。 希望得到 dataForTemplate 变量的值。 脚本如下。

      <script>
        var customizedContactUsUrl =
        var dataForTemplate = {
          redirectToOrg : 'Redirecting you to your organization...',
          actionUrl:document.getElementById('actionUrl').action,
          relayState:'3IUARpZFHyXO6th5WtiE5tJLmrHRpc',
          samlValue:'PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPS,
          samlKey:'SAMLResponse',
        var validEmailInputHint = 'Enter a valid email address, formatted as user@company.com.'
        </script>

Tried the following code but not working:

pattern = re.compile('var dataForTemplate = (.);')
            if(pattern.match(str(required_data.string))):
                data = pattern.match(required_data.string)
                print("data",data)
                stock = json.loads(data.groups()[0])
                print(stock)
    
3 个评论
json.loads( "{" + required_data.string.split('{')[1].split('}')[0] + "}" ) ?
document.getElementById('actionUrl').action, ,这在JSON数据中是不正确的元素。你必须跳过这个元素或者运行JavaScript来从这个函数中获取值。而且它需要 Selenium
文本 "不工作"`是最无用的信息。你应该描述它。我们无法运行代码来查看问题所在。如果你得到了错误信息,那么你应该把它放在问题中(而不是评论中),作为文本(而不是图片)。
python
web-scraping
beautifulsoup
pattern-matching
Puja Neve
Puja Neve
发布于 2019-12-16
2 个回答
QHarr
QHarr
发布于 2019-12-16
已采纳
0 人赞同

你的regex很可能会失败,因为 . 会匹配除行结束符以外的单个字符,然后期待一个 ; 。你想进行匹配,直到你碰到结尾的},所以你需要进行懒人匹配。

var dataForTemplate = ([\s\S]+?})

解释一下。

burney
burney
发布于 2019-12-16
0 人赞同

在我下面的代码中,有太多的分叉,但希望能有所帮助。

from bs4 import BeautifulSoup
url = 'home.html'
with open(url) as file:
    soup = BeautifulSoup(file, 'html.parser')
script_text = str(soup.find('script'))
my_var = script_text.split('var')[2]
my_var_value = my_var.split(' = ')[1]
print(my_var_value)
#     redirectToOrg : 'Redirecting you to your organization...',
#     actionUrl:document.getElementById('actionUrl').action,