美文网首页
python爬虫----requests的简单应用

python爬虫----requests的简单应用

作者: 梵高先生uu | 来源:发表于2019-01-01 19:17 被阅读0次

    1####

    Requests 继承了urllib的所有特性。Requests支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的URL和 POST 数据自动编码.
    安装方式

    利用 pip 安装 或者利用 easy_install 都可以完成安装:

    $ pip3 install requests
    

    最基本的GET请求可以直接用get方法

    response = requests.get("http://www.baidu.com/")
    # 也可以这么写
    # response = requests.request(
        "get", 
        "http://www.baidu.com/"
    )
    

    简单的post请求

    import requests
    
    req_url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"
    
    #分析表单数据
    formdata = {
        'i': '老鼠爱大米',
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_CLICKBUTTION',
        'typoResult': 'false',
    }
    
    #添加请求头
    req_header = {
        'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
    }
    
    response = requests.post(
        req_url, 
        data = formdata, 
        headers = req_header
    )
    
    #print (response.text)
    # 如果是json文件可以直接显示
    print (response.json())
    
    

    相关文章

      网友评论

          本文标题:python爬虫----requests的简单应用

          本文链接:https://www.haomeiwen.com/subject/xcqolqtx.html