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

请教关于 urllib.request.urlopen 方法的问题

  •  
  •   saximi · 2017-09-22 20:52:07 +08:00 · 2157 次点击
    这是一个创建于 2405 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import urllib.request 
    
    def download(url): 
        print("DOWNLOADING:",url) 
        try: 
            html=urllib.request.urlopen(url).read() 
            print(html) 
        except Exception as e: 
            print("DOWNLOAD ERROR:",e) 
            html=None 
        return html 
    
    download("http://www.ccb.com/")
    
    上面的代码输出如下:
    DOWNLOADING: http://www.ccb.com/
    b'<SCRIPT LANGUAGE="JavaScript">\n  window.location="/cn/home/indexv3.html";\n</SCRIPT>\n\n\n'
    
    请问,这个 html 的输出从网页的源码中是找不到的,为何 html 输出后会是这样的内容?谢谢!
    
    
    8 条回复    2017-09-23 14:44:57 +08:00
    misaka19000
        1
    misaka19000  
       2017-09-22 21:43:57 +08:00
    ➜ ~ curl http://www.ccb.com/
    <SCRIPT LANGUAGE="JavaScript">
    window.location="/cn/home/indexv3.html";
    </SCRIPT>

    没毛病
    saximi
        2
    saximi  
    OP
       2017-09-22 21:45:54 +08:00
    @misaka19000 我倒是没说这个结果有错,我只是不理解这个 html 是个什么东西,为何是显示这些内容,并且这个字符串其实并不存在于这个网页的源代码中
    zhusimaji
        3
    zhusimaji  
       2017-09-22 22:01:44 +08:00 via iPhone
    @saximi 那个是 js,你要等 js 加载完才能访问到真正的网页,你应该访问这个地址 www.ccb.com/cn/home/indexv3.html
    dangyuluo
        4
    dangyuluo  
       2017-09-22 22:09:51 +08:00
    你获取的是一小段 JS 代码,让你跳转到他们的 indexv3.html 页面。不知道这么做的意义在哪。
    ffkjjj
        5
    ffkjjj  
       2017-09-22 22:12:09 +08:00 via iPhone
    @saximi
    访问 http://www.ccb.com 时的默认网页源码就是你爬到的字符串内容。
    通过浏览器访问到的页面是 http://www.ccb.com/cn/home/indexv3.html,那已经是重定向后的页面啦。
    sola97
        6
    sola97  
       2017-09-22 23:24:52 +08:00
    没学过 html 么。。
    saximi
        7
    saximi  
    OP
       2017-09-23 05:44:25 +08:00
    @zhusimaji
    @dangyuluo
    @ffkjjj 感谢大家指点,确实没有系统地学过 HTML
    Telegram
        8
    Telegram  
       2017-09-23 14:44:57 +08:00 via iPhone
    浏览器直接访问也是这个源码,然后浏览器会自动执行这个代码,跳转到那个新的页面。
    但是你的 py 不会跳,因为他不执行这个跳转的 js
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5780 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 06:27 · PVG 14:27 · LAX 23:27 · JFK 02:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.