V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
mochanight
V2EX  ›  Python

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

  •  
  •   mochanight · 2018-01-09 18:36:55 +08:00 · 2348 次点击
    这是一个创建于 2271 天前的主题,其中的信息可能已经有所发展或是发生改变。
    服务器返回结果如下:

    <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 变量。如果为空变量也为空。
    9 条回复    2018-01-10 16:13:01 +08:00
    Pythonerxiaobai
        1
    Pythonerxiaobai  
       2018-01-09 18:43:44 +08:00   ❤️ 1
    返回值就是列表啊,列表里面没值而已
    mochanight
        2
    mochanight  
    OP
       2018-01-09 18:45:11 +08:00
    @Pythonerxiaobai 对的,我就是想问能不能不返回列表,直接返回字符串
    ranleng
        3
    ranleng  
       2018-01-09 18:48:50 +08:00   ❤️ 2
    lxml xpath ?
    wenbinwu
        4
    wenbinwu  
       2018-01-09 18:50:54 +08:00   ❤️ 1
    @mochanight 1L 的意思是,re.matches 返回值就是 list,你 print 的话就有大括号
    `Return all non-overlapping matches of pattern in string, as a list of strings.`
    你遍历这个列表就是了
    空的话就是没 match 到
    AlisaDestiny
        5
    AlisaDestiny  
       2018-01-09 18:53:15 +08:00   ❤️ 1
    你一定没有看文档。
    re.findall()返回的是一个所有匹配的列表。如果你确定最多只会匹配到一个,你就直接判断是否为 None,然后取 matchs[0]
    mochanight
        6
    mochanight  
    OP
       2018-01-09 18:53:20 +08:00
    = = 现在直接这样了 解决了
    if matches == []:
    matches = ""
    else:
    print(matches[0])
    flym0te
        7
    flym0te  
       2018-01-09 18:54:05 +08:00 via Android   ❤️ 1
    print(matches[0])试下
    frostming
        8
    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
        9
    vxoge  
       2018-01-10 16:13:01 +08:00
    print(matches[0])
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2781 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 80ms · UTC 12:20 · PVG 20:20 · LAX 05:20 · JFK 08:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.