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
zasilla
V2EX  ›  Python

新手学习正则练习时碰到的一个问题

  •  
  •   zasilla · 2018-10-21 08:52:47 +08:00 · 2272 次点击
    这是一个创建于 1985 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python 版本 3.6.5,代码如下:

    import requests

    import re

    content = requests.get('http://book.douban.com/').text

    pattern = re.compile('<li.?href="(.?)".?title="(.?)".*?', re.S)

    results = re.findall(pattern, content)

    print(results)

    代码在 results = re.findall(pattern, content)这里卡住了,如果将

    pattern = re.compile('<li.?href="(.?)".?title="(.?)".*?', re.S)

    去掉一个()

    pattern = re.compile('<li.?title="(.?)".*?', re.S)

    就能正确的运行,请问我是哪里出错了?希望大家指教

    7 条回复    2018-10-23 15:01:01 +08:00
    summerwar
        1
    summerwar  
       2018-10-21 09:35:34 +08:00
    正则不对,?表示重复零次或一次,网址和标题哪有那么短
    PulpFunction
        2
    PulpFunction  
       2018-10-21 09:45:54 +08:00   ❤️ 1
    写代码不能试着写啊…

    1 解析网页直接上正则不太好,2requests 不加 head 容易被封

    非要上正则的话,你把 findall 参数搞混错了…

    建议再看文档: http://www.runoob.com/python/python-reg-expressions.html

    还可以了解一下 Beautifulsoup 等等
    SpiderXiantang
        3
    SpiderXiantang  
       2018-10-21 09:55:40 +08:00
    了解下 xpath 不过正则还是得学的
    GreatTony
        4
    GreatTony  
       2018-10-21 10:10:44 +08:00
    html 用正则解析效率很低和出错率挺高的,用这个库吧: https://github.com/kennethreitz/requests-html,requests 的作者的另一库,非常好用
    frostming
        5
    frostming  
       2018-10-22 10:48:33 +08:00
    学正则的时候验证一下表达式
    http://tool.oschina.net/regex
    wersonliu9527
        6
    wersonliu9527  
       2018-10-22 15:16:11 +08:00
    不想正则搞晕,直接用谷歌浏览器的 copy xpath 功能加上 xpath helper 插件吧
    canwushuang
        7
    canwushuang  
       2018-10-23 15:01:01 +08:00
    问题在于问号 “?” 问好表示非贪婪
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3153 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:40 · PVG 20:40 · LAX 05:40 · JFK 08:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.