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

Postman 可以请求到数据,为什么 Python 的 requests 就不行呢

  •  1
     
  •   shawlib · 2017-12-02 15:01:29 +08:00 · 3059 次点击
    这是一个创建于 2347 天前的主题,其中的信息可能已经有所发展或是发生改变。

    知乎的请求链接 “ https://www.zhihu.com/r/search?q=留学中介&range=1d&type=content&offset=0

    postman 返回结果是正常的 json

    用 requests 就是 500

    requests 没带任何参数

    不懂..@_@

    8 条回复    2017-12-03 01:00:52 +08:00
    ferrum
        1
    ferrum  
       2017-12-02 15:09:25 +08:00 via iPhone
    postman 可能打开了浏览器 cookies 同步。
    iyaozhen
        2
    iyaozhen  
       2017-12-02 15:16:41 +08:00   ❤️ 1
    postman 可以生成 Python 代码,你对比下就明白了
    lance6716276
        3
    lance6716276  
       2017-12-02 15:29:08 +08:00
    headers
    mringg
        4
    mringg  
       2017-12-02 15:33:30 +08:00
    试下换个 UA 试试吧
    mringg
        5
    mringg  
       2017-12-02 15:33:45 +08:00
    curl 'https://www.zhihu.com/r/search?q=%E7%95%99%E5%AD%A6%E4%B8%AD%E4%BB%8B&range=1d&type=content&offset=0' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
    shawlib
        6
    shawlib  
    OP
       2017-12-02 23:48:32 +08:00
    @ferrum 用 Python 可以完全模仿出来么?
    @mringg 还是不行呢
    @lance6716276 换 headers 也不行
    @iyaozhen 用 postman 生成的代码是
    ```
    import requests

    url = "https://www.zhihu.com/r/search"

    querystring = {"q":"留学","range":"1d","type":"content","offset":"0"}

    headers = {
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "96abb04d-fc38-6632-703e-0db88e60b9ca"
    }

    response = requests.request("GET", url, headers=headers, params=querystring)

    print(response.text)
    ```
    还是报 500
    ferrum
        7
    ferrum  
       2017-12-03 00:30:28 +08:00
    之前没注意,原来知乎的接口不需要登录也能使用。

    在你上面贴的代码里的 `headers` 加上 User-Agent 就可以了。

    'user-agent': "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
    shawlib
        8
    shawlib  
    OP
       2017-12-03 01:00:52 +08:00
    @ferrum 多谢多谢!^_^
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   6092 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 01:53 · PVG 09:53 · LAX 18:53 · JFK 21:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.