python - 使用正则表达式解析字符串python3

标签 python python-3.x parsing beautifulsoup html-parsing

我正在尝试从以下字符串访问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);
                }
            });

如何使用正则表达式解析字符串中的值?我知道一旦我解析了它,我就可以将它作为 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 这样的大包来实现此目的;您只需使用 Python re 包即可轻松解析出 gSecureToken 的值。

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

import re

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

然后,我们可以使用您的测试字符串:

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);
                }
            });
"""

最后我们可以在测试字符串中搜索正则表达式:

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

这给了我们所需的值(value):

7b9854390a079b03cce068b577cd9af6686826b8

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

关于python - 使用正则表达式解析字符串python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57318195/

相关文章:

python - 我该如何过滤日期

c++ - Charniak 解析器错误

python - 从 Pandas 的日期时间列中减去一年

python tkinter Radiobuttons - 两个按钮在显示之前都被选中

python - 迭代使用 groupby apply 函数

parsing - Elm 解析器循环不会终止

python - lxml 无法解析 <table>?

Python3 : How do I import an excel spreadsheet into python project?(我使用 repl.it 网站学习 python3)

python - 如何创建 pyserial 可以读取的虚拟串行?

python-3.x - 如何使用 BS4 抓取 Shopee 用户评论