zoukankan      html  css  js  c++  java
  • python爬虫-2 requests使用

    基本用法-获取内容

    import requests
    
    headers = {'Accept-Encoding': 'gzip, deflate',
               'Accept-Language': 'zh-CN,zh;q=0.8',
               'Connection': 'keep-alive',
               'content-type': 'application/json',
               'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0',
               'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'}
    
    url = 'http://www.people.com.cn/'
    r = requests.get(url=url, headers=headers)
    r.encoding='utf-8'
    # byte类型内容
    # print(str(r.content))
    # unicode内容
    # print(r.text)
    # 响应头
    print(r.headers)
    # cookies
    print(r.cookies)
    # 状态码
    print(r.status_code)
    

    模拟登录,模拟请求,状态保持等 

    #构建一个有Cookie内容的请求
    headers_had_JSEID = {'Accept-Encoding':'gzip, deflate','Accept-Language':'zh-CN,zh;q=0.8','Connection':'keep-alive',
                'Cookie':'JSESSIONID='+in_jsessionid,'content-type': 'application/json','User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0',
                'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'}
    
    #get模拟请求
    source_xj=requests.get(url_xj,headers=headers_had_JSEID)

    会话维持

    每次get相当于重新用个浏览器访问新网站,Session相当于在网站内浏览不同页面,可以维持之前的记录

    # 会话维持
    s=requests.Session()
    r=s.get(url=url)
    print(r.text)
  • 相关阅读:
    深入理解Http协议
    Http协议详解
    过滤器、监听器、拦截器的区别
    HTTP状态代码集
    理解XML-RPC
    Axis2 解析
    REST SOAP XML-RPC分析比较
    Spring 第一天课程
    Spring 框架学习 有用
    数据库主从复制,读写分离,负载均衡,分表分库的概念 没用
  • 原文地址:https://www.cnblogs.com/onenoteone/p/12441695.html
Copyright © 2011-2022 走看看