我试图从以下string访问gSecureToken

$("#ejectButton").on("click", function(e) {
            $("#ejectButton").prop("disabled", true);
            $.ajax({
                url : "/apps_home/eject/",
                type : "POST",
                data : { gSecureToken : "7b9854390a079b03cce068b577cd9af6686826b8" },
                dataType : "json",
                success : function(data, textStatus, xhr) {
                    $("#smbStatus").html('');
                    $("#smbEnable").removeClass('greenColor').html('OFF');
                    showPopup("MiFi Share", "<p>Eject completed. It is now safe to remove your USB storage device.</p>");
                },
                error : function(xhr, textStatus, errorThrown) {
                    //undoChange($toggleSwitchElement);
                    // If auth session has ended, force a new login with a fresh GET.
                    if( (xhr.status == 401) || (xhr.status == 403) || (xhr.status == 406) ) window.location.replace(window.location.href);
                }
            });

如何使用正则表达式解析string中的值?我知道一旦解析了,我就可以将它加载为JSON。

我目前的代码不使用正则表达式,它只是处理使用BeautifulSoup来解析一些html。到目前为止,这是我的代码:

from bs4 import BeautifulSoup

class SecureTokenParser:

    @staticmethod
    def parse_secure_token_from_html_response(html_response):
        soup = BeautifulSoup(html_response, 'html.parser')
        for script_tag in soup.find_all("script", type="text/javascript"):
            print(script_tag)

我知道它并不多,但我认为这是将内容打印到终端的一个很好的起点。如何使用正则表达式解析gSecureToken然后将其加载为JSON?

分析解答

不需要像BeautifulSoup那样回复大型package;您只需使用Python re package即可轻松解析gSecureToken的值。

我假设您想要解析gSecureToken的值。然后,您可以创建正则表达式模式:

import re

pattern = r'{\s*gSecureToken\s*:\s*"([a-z0-9]+)"\s*}'

然后,我们可以使用您的测试string:

test_str = """
$("#ejectButton").on("click", function(e) {
            $("#ejectButton").prop("disabled", true);
            $.ajax({
                url : "/apps_home/eject/",
                type : "POST",
                data : { gSecureToken : "7b9854390a079b03cce068b577cd9af6686826b8" },
                dataType : "json",
                success : function(data, textStatus, xhr) {
                    $("#smbStatus").html('');
                    $("#smbEnable").removeClass('greenColor').html('OFF');
                    showPopup("MiFi Share", "<p>Eject completed. It is now safe to remove your USB storage device.</p>");
                },
                error : function(xhr, textStatus, errorThrown) {
                    //undoChange($toggleSwitchElement);
                    // If auth session has ended, force a new login with a fresh GET.
                    if( (xhr.status == 401) || (xhr.status == 403) || (xhr.status == 406) ) window.location.replace(window.location.href);
                }
            });
"""

最后我们可以在测试string中搜索我们的正则表达式:

match = re.search(pattern, test_str)
matching_string = match.groups()[0]
print(matching_string)

这给了我们所需的价值:

7b9854390a079b03cce068b577cd9af6686826b8

您可以通过访问此链接来了解此正则表达式的工作原理:www.regexr.com/4ihpd