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

请教一下, HttpConnection 和 urlopen 在处理 URL 时,有什么不同的地方吗?

  •  
  •   twlsoft · 2016-09-08 16:46:39 +08:00 · 1655 次点击
    这是一个创建于 2788 天前的主题,其中的信息可能已经有所发展或是发生改变。

    主要场景是这样的,我有一段 URL ,用于对百度贴吧进行签到

    使用 HttpConnection 的代码如下:

    conn = http.client.HTTPConnection('tieba.baidu.com', 80)
    conn.request('GET', '/mo/q---{0}/sign?tbs={1}&fid={2}&kw={3}'.format(urllib.parse.quote(BAIDUID, 'utf-8'), tbs, fid, urllib.parse.quote(tieba, 'utf-8')))
    
    resp = conn.getresponse()
    

    使用 urlopen 的例子如下

    url = 'http://tieba.baidu.com/mo/q---{0}/sign?tbs={1}&fid={2}&kw={3}'.format(urllib.parse.quote(BAIDUID, 'utf-8'), tbs, fid, urllib.parse.quote(tieba, 'utf-8'))
    urllib.request.urlopen(url)
    

    两个 URL 地址是完全一样的,然而使用 HttpConnection 的情况下,虽然返回的 code 是 200 ,同时 read 出来的也是正常打开贴吧的源代码,可是贴吧却没有签到成功, 可是使用 urlopen 这个方式却签到成功了。

    请问下各位,这是什么原因导致的呢?

    5 条回复    2016-09-09 09:24:50 +08:00
    q397064399
        1
    q397064399  
       2016-09-08 18:56:50 +08:00
    建议用 fiddler4 抓包看看是不是 useragent 有区别,最好还是分析下 http 报文 http 报文还是很好懂的
    q397064399
        2
    q397064399  
       2016-09-08 18:59:09 +08:00
    我猜测是 useragent 的原因
    binux
        3
    binux  
       2016-09-08 19:22:19 +08:00
    为什么要这么折磨自己?
    twlsoft
        4
    twlsoft  
    OP
       2016-09-09 09:24:26 +08:00
    @q397064399 嗯嗯,明白,我去试一试~谢谢~~
    twlsoft
        5
    twlsoft  
    OP
       2016-09-09 09:24:50 +08:00
    @binux 啊?什么意思呢?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1238 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 23:46 · PVG 07:46 · LAX 16:46 · JFK 19:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.