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库提取返回的值?小白求助
返回值就是列表啊,列表里面没值而已
对的,我就是想问能不能不返回列表,直接返回字符串
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])


