image-1655306455473

#一.前言
1.requests是使用Apache2 licensed 许可证的HTTP库。
2.用python编写。比urllib2模块更简洁。
3.Request支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动响应内容的编码,支持国际化的URL和POST数据自动编码。
4.在python内置模块的基础上进行了高度的封装,从而使得python进行网络请求时,变得人性化,使用Requests可以轻而易举的完成浏览器可有的任何操作。
5.现代,国际化,友好。
6.requests会自动实现持久连接keep-alive

二. 安装

pip install requests

注意,如果是使用的pycharm且连接的是虚拟机或远程主机的,装完之后一定要重启项目才能被识别到

#三.基本使用
1 .导入库

import requests

2 . 发送简单的请求

 import requests 
r = requests.get('http://httpbin.org/get)       # 最基本的不带参数的get请求
r1 = requests.get(url='http://httpbin.org/get', params={'wd': 'python'})      # 带参数的get请求
  1. requests库还提供了完整的HTTP/1.1的所有请求方法
requests.get(‘https://github.com/timeline.json’)                                # GET请求
requests.post(“http://httpbin.org/post”)                                        # POST请求
requests.put(“http://httpbin.org/put”)                                          # PUT请求
requests.delete(“http://httpbin.org/delete”)                                    # DELETE请求
requests.head(“http://httpbin.org/get”)                                         # HEAD请求
requests.options(“http://httpbin.org/get” )                                     # OPTIONS请求
  1. 响应的内容
r.encoding                       #获取当前的编码
r.encoding = 'utf-8'             #设置编码
r.text                           #以encoding解析返回内容。字符串方式的响应体,会自动根据响应头部的字符编码进行解码。
r.content                        #以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。

r.headers                        #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None

r.status_code                     #响应状态码
r.raw                             #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read()   
r.ok                              # 查看r.ok的布尔值便可以知道是否登陆成功
 #*特殊方法*#
r.json()                         #Requests中内置的JSON解码器,以json形式返回,前提返回的内容确保是json格式的,不然解析出错会抛异常
r.raise_for_status()             #失败请求(非200响应)抛出异常

5.超时

r = requests.get('url',timeout=1)           #设置秒数超时,仅对于连接有效

6.代理

proxies = {'http':'ip1','https':'ip2' }
requests.get('url',proxies=proxies)

#Get 请求示例
借鉴云教程中心的图

# 1、无参数实例
  
import requests
ret = requests.get('https://github.com/timeline.json')
print(ret.url)
print(ret.text)
  
# 2、有参数实例
  
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.get("http://httpbin.org/get", params=payload)
print(ret.url)
print(ret.text)

#Post 请求示例

# 1、基本POST实例
  
import requests
  
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.post("http://httpbin.org/post", data=payload)
  
print(ret.text)
  
  
# 2、发送请求头和数据实例
  
import requests
import json
  
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
  
ret = requests.post(url, data=json.dumps(payload), headers=headers)
  
print(ret.text)
print(ret.cookies)

#四.实战,抓取
http://wz.sun0769.com/index.php/question/questionType?type=4
的内容测试下

image-1655306555723

image-1655306561176

image-1655306565426

image-1655306570853

#希望进来看的大佬指出错误以及改进建议,万分感谢

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/10/14 23:41
# @Author  : kaixuan
# @Site    : 
# @File    : requests_test.py
# @Software: PyCharm
import re
import json
import random
import requests


def home_page(page,headers):
    url = 'http://wz.sun0769.com/index.php/question/questionType?type=4&page={}'.format(page)
    r = requests.get(url,headers=headers)
    res = r.content.decode('GBK',errors='strict')
    title_urls = re.findall(r'<tr>.*?<td width=.*?bgcolor=".*?">(.*?)</td>.*?</a> <a href="(.*?)" title="(.*?)" target=.*?',res,re.S)
    return title_urls

def detail_page(title_urls,lists,headers):
    for title_url in title_urls:
        # print('第{}次'.format(n))
        print('编号是:{}  标题是:{}  网址是:{}{}'.format(title_url[0],title_url[2],title_url[1],'\r\n'))
        context = requests.get(title_url[1],headers=headers)
        context_detail = context.content.decode('GBK',errors='strict')
        detail = re.findall(r'<div class="wzy3_2"><span style="color:#666">网友:(.*?)发言时间:(.*?)&nbsp; </span></div>',context_detail,re.S)
        context_detail = re.findall(r'<table .*?>.*?<tr>.*?<td class="txt16_3".*?>(.*?)</td>.*</tr>',context_detail,re.S)
        context_detail=context_detail[0].replace('&nbsp','').replace(';','').replace('<br />',' ').replace('<br/>','').replace(' ' ,'').replace('"','\'')
        if 'img' in context_detail:
            context_detail = re.findall(r'<div.*class=\'textpic\'.*src=\'(.*?)\'.*?<divclass=\'contentext\'>(.*?)</div>',context_detail,re.S)
        print('内容是:'+'\r\n'+'{}'.format(context_detail)+'\r\n')
        # data = {'author':'','time':'','title': '', 'url': '', 'context': '', 'img_url': ''}
        data={}
        data['id']=title_url[0]
        data['author'] = detail[0][0]
        data['time'] = detail[0][-1]
        data['title']=title_url[2]
        data['url']=title_url[1]
        # lists[title_url[0]]['title'] = title_url[2]
        # lists[title_url[0]]['url'] = title_url[1]
        try :
            if type(context_detail[0]) is tuple :
                data['context'] = context_detail[0][-1]
                data['img_url'] ='http://wz.sun0769.com'+ context_detail[0][0]
            else:
                data['context'] = context_detail
        except IndexError as e:
            print('内容匹配错误!!',e)
        lists['obj'].append(data)
    return lists

if __name__ == '__main__':
    User_Agent = [
       'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0',
       'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
    ]
    random.shuffle(User_Agent)
    headers={
        'User-Agent': User_Agent[0],
        'Host': 'wz.sun0769.com',
        'Referer': 'http://wz.sun0769.com/index.php/question/questionType?type=4',
    }
    lists = {'obj':[]}
    # t_list = []
    for page in range(0,91,30):
        print(headers)
        title_urls = home_page(page,headers)
        # print(len(title_urls))
        lists = detail_page(title_urls,lists,headers)
    #     t = threading.Thread(target=detail_page, args=(title_urls,lists))
    #     t_list.append(t)
    #
    #     # 启动线程
    # for t in t_list:
    #     t.start()
    #
    #     # 等待所有线程结束
    # for t in t_list:
    #     t.join()
    print(lists)

    with open('test.json','w+',encoding='GBK')as f:
        f.write(json.dumps(lists))

上一篇 下一篇