Python 请求 header 。如何解析这个? ast 的语法无效?

标签 python ssl python-requests http-headers tls1.2

我想将标题字符串转换为字典。字符串来自各种来源,因此格式有点复杂。

这是一个例子:

import ast
import re

header="{'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'", 'X-Content-Type-Options': 'nosniff', 'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}"

headerDict = ast.literal_eval(header)

当我运行它时,我得到这个错误:

SyntaxError: invalid syntax

我更改了字符串中的两个双引号:"default-src [...] https://a.1password.eu/" from """

但是还是有错误。显然来自包含单引号的 'self' 的内容。

我根本不应该更改标题内容。但是,如果我应用单个规则,例如,将每个 " 替换为 "" 这是可能的解决方案。因为我需要解析 header 。它应该保持其原始状态数据,我不应该更改任何内容。

这种情况下的解决方案是什么?这是一个示例,但我希望看到其他变体。如何将类似字典的字符串转换成字典?

最佳答案

使用三引号字符串:

import ast

header = """{'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'", 'X-Content-Type-Options': 'nosniff', 'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}"""

ast.literal_eval(header)

输出:

{'Content-Type': 'text/html',
 'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'",
 'X-Content-Type-Options': 'nosniff',
 'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}

关于Python 请求 header 。如何解析这个? ast 的语法无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56085899/

相关文章:

python - 获取函数中必需和非必需参数的数量

Python 与 Julia 速度比较

ssl - 在 Python3.6 中使用 http.client 返回 [SSL : UNKNOWN_PROTOCOL]

执行 HTTP 调用时打印一个点到控制台的 Python 函数

python - 如何避免使用日期时间列的 pandas mean() 性能不佳

python - 使用 isinstance 测试 Unicode 字符串

java - 在我的应用程序中硬编码我的 keystore 的密码可以吗?

apache - IE 突然停止加载 HTML 页面

Python数据输出到Excel

python - 脚本突然停止爬取,无错误无异常