从请求响应中查找以单词开头的完整字符串

Find complete string starting with a word from request response

如何从请求对象中获取与单词匹配的完整行

例如我有 response=request.get(url) 和 print(response.text) 并假设如果输出有以下几行,我正在尝试获取完整的单词开头file_path 和预期结果为“file_path:/opt/temp”

用户:abcd
search_file: f-abc-123
file_path: /opt/temp
分支:发展
email_to: abc@gmail.com
版本:1.10.00

下面是我的代码,但似乎不起作用

import re
import requests
response=request.get("https://artifactory.com",header=(..),verify=False)
res=re.search(r'file_path\w+',response.text)
print(res.group(0))

我得到的输出:
file_path

预期输出:
file_path: /opt/temp

试试这个,

#until a newline(\n) is hit, consider all characters.
res= re.search(r'file_path[^\n]+', response.text)
print(res.group(0))

output: 'file_path: /opt/temp'

如果您真的想逐行解析并确保在与您的字符串匹配的情况下得到整行,那么您可以沿换行符拆分文本输出并检查每一行是否有您要查找的文本

r = requests.get("https://artifactory.com",header=(..),verify=False)
lines = r.text.split('\n')
for line in lines:
  if 'file_path' in line:
    print(line)

但是,如果您返回的数据是 json 格式,我怀疑它可能来自您上面的描述,那么您绝对应该利用 json 格式来处理它而不是逐行解析。您可以在 json 响应中参考 file_path 的密钥,例如

r = requests.get("https://artifactory.com",header=(..),verify=False)
data = r.json()
print('file_path: ' + data['file_path'])

这些方法不需要正则表达式。如果您知道您正在处理 json 响应而不仅仅是一些未知格式的文本响应,那么 json 方法是最好的。