Python中如何使用requests库提取返回的值?小白求助

服务器返回结果如下:

<Result>

<accessToken></accessToken>

<appId></appId>

<createTime>0</createTime>

<errorCode>1001</errorCode>

<errorMsg>请重新进入</errorMsg>

<imgUrl></imgUrl>

</Result>

需要提取 imgUrl 中的值,这里的值有时为空,有时是有数据的。

现在用的 re 模块

matches = re.findall(’(?:<imgUrl>)(.+)(?:</imgUrl>)’,response.text)

这里出现了一个问题:
print(matches)
[]

为啥有大括号,我不需要这个大括号啊,我需要的是纯字符串定义为 matches 变量。如果为空变量也为空。
Python中如何使用requests库提取返回的值?小白求助


10 回复

返回值就是列表啊,列表里面没值而已


import requests

# 1. 基本GET请求获取响应内容
response = requests.get('https://api.example.com/data')
# 直接获取文本内容
text_content = response.text
# 如果是JSON格式,直接解析为字典
json_data = response.json()

# 2. 提取特定字段(假设返回JSON格式)
if response.status_code == 200:
    data = response.json()
    # 提取嵌套字段
    user_name = data['user']['name']
    items = data['items'][0]['id']
else:
    print(f"请求失败: {response.status_code}")

# 3. 处理XML/HTML响应(使用lxml解析)
from lxml import etree
html_response = requests.get('https://example.com')
tree = etree.HTML(html_response.text)
title = tree.xpath('//title/text()')[0]

# 4. 处理响应头信息
headers = response.headers
content_type = headers['Content-Type']

# 5. 完整示例:获取GitHub用户信息
def get_github_user(username):
    url = f'https://api.github.com/users/{username}'
    resp = requests.get(url)
    
    if resp.status_code == 200:
        user_data = resp.json()
        return {
            'name': user_data.get('name'),
            'company': user_data.get('company'),
            'public_repos': user_data.get('public_repos')
        }
    else:
        return None

# 使用示例
user_info = get_github_user('octocat')
if user_info:
    print(f"用户名: {user_info['name']}")
    print(f"公司: {user_info['company']}")
    print(f"公开仓库数: {user_info['public_repos']}")

关键点:

  1. response.text 获取文本内容
  2. response.json() 自动解析JSON响应
  3. response.status_code 检查请求状态
  4. response.headers 获取响应头信息

对于JSON数据直接用.json()转字典后按键取值,其他格式需要相应解析库。

总结:根据响应格式选择正确的解析方法。

对的,我就是想问能不能不返回列表,直接返回字符串

lxml xpath ?

1L 的意思是,re.matches 返回值就是 list,你 print 的话就有大括号
Return all non-overlapping matches of pattern in string, as a list of strings.
你遍历这个列表就是了
空的话就是没 match 到

你一定没有看文档。
re.findall()返回的是一个所有匹配的列表。如果你确定最多只会匹配到一个,你就直接判断是否为 None,然后取 matchs[0]

= = 现在直接这样了 解决了
if matches == []:
matches = ""
else:
print(matches[0])

print(matches[0])试下

看你的意思,空是空字符串的意思吗?那就:
print(matches and matches[0] or ‘’)

不过可以一开始就不返回列表:
matches = re.search(’(?:<imgUrl>)(.*?)(?:</imgUrl>)’,response.text).group(1)
print(matches)

print(matches[0])

回到顶部