小白求助, request 中如何提取返回的值

2018-01-09 18:36:55 +08:00
 mochanight
服务器返回结果如下:

<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 变量。如果为空变量也为空。
2386 次点击
所在节点    Python
9 条回复
Pythonerxiaobai
2018-01-09 18:43:44 +08:00
返回值就是列表啊,列表里面没值而已
mochanight
2018-01-09 18:45:11 +08:00
@Pythonerxiaobai 对的,我就是想问能不能不返回列表,直接返回字符串
ranleng
2018-01-09 18:48:50 +08:00
lxml xpath ?
wenbinwu
2018-01-09 18:50:54 +08:00
@mochanight 1L 的意思是,re.matches 返回值就是 list,你 print 的话就有大括号
`Return all non-overlapping matches of pattern in string, as a list of strings.`
你遍历这个列表就是了
空的话就是没 match 到
AlisaDestiny
2018-01-09 18:53:15 +08:00
你一定没有看文档。
re.findall()返回的是一个所有匹配的列表。如果你确定最多只会匹配到一个,你就直接判断是否为 None,然后取 matchs[0]
mochanight
2018-01-09 18:53:20 +08:00
= = 现在直接这样了 解决了
if matches == []:
matches = ""
else:
print(matches[0])
flym0te
2018-01-09 18:54:05 +08:00
print(matches[0])试下
frostming
2018-01-10 10:49:47 +08:00
看你的意思,空是空字符串的意思吗?那就:
print(matches and matches[0] or '')

不过可以一开始就不返回列表:
matches = re.search('(?:<imgUrl>)(.*?)(?:</imgUrl>)',response.text).group(1)
print(matches)
vxoge
2018-01-10 16:13:01 +08:00
print(matches[0])

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/421456

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX