Python爬虫系列之requests模块

之前用php的时候也爬取过别人网站的数据,那时候采集数据,感觉自从python火起来之后就变为爬虫了,甚至让人觉得一说到爬虫代指的就是python了,不过想想来看使用python制作爬虫比当年使用php采集简直容易简单的太多了,php那时候只能自个写正则进行繁琐的匹配,python不光可以使用正则,第三方库使用xpathBeautifulSoup进行目标解析让我不用正则就能轻松爬取到想要的数据,一个字“太爽了”!!!

Requests 唯一的一个非转基因Python HTTP 库,人类可以安全享用。

警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症、冗余代码症、重新发明轮子症、啃文档症、抑郁、头疼、甚至死亡。

Requests简介

requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求。功能强大,用法简洁高效。在爬虫领域中占据着半壁江山的地位。

requests与urllib模块对比

urllibrequests
手动处理url编码自动处理url编码
手动处理post请求参数自动处理post请求参数
处理cookie和代理操作繁琐简化cookie和代理操作

安装

1
pip install requests

主要方法

方法解释
requests.request()构造一个请求,支持以下各种方法
requests.get()获取html的主要方法
requests.head()获取html头部信息的主要方法
requests.post()html网页提交post请求的方法
requests.put()html网页提交put请求的方法
requests.patch()html提交局部修改的请求
requests.delete()html提交删除请求

requests.get()

语法:

1
2
3
4
r=requests.get(url,params,**kwargs)
# url: 需要爬取的网站地址。
# params: 翻译过来就是参数, url中的额外参数,字典或者字节流格式,可选。
# **kwargs : 12个控制访问的参数
url

要请求的目标地址

params

字典或字节序列, 作为参数增加到url中,使用这个参数可以把一些键值对以?key1=value1&key2=value2的模式增加到url

**kwargs

例如:

1
2
kv = {'key1':' values', 'key2': 'values'}
r = requests.get('[http:www.python123.io/ws](http://www.python123.io/ws)', params=kw)
  • data:字典,字节序或文件对象,重点作为向服务器提供或提交资源是提交,,作为request的内容,与params不同的是,data提交的数据并不放在url链接里, 而是放在url链接对应位置的地方作为数据来存储。,它也可以接受一个字符串对象。

  • jsonjson格式的数据, json合适在相关的htmlhttp相关的web开发中非常常见, 也是http最经常使用的数据格式, 他是作为内容部分可以向服务器提交。

    例如:

    1
    2
    kv = {'key1': 'value1'}
    r = requests.post('http://python123.io/ws', json=kv)
  • headers:字典是http的相关语,对应了向某个url访问时所发起的~的头i字段, 可以用这个字段来定义http的访问的http头,可以用来模拟任何我们想模拟的浏览器来对url发起访问。

    例子:

    1
    2
    hd = {'user-agent': 'Chrome/10'} 
    r = requests.post('http://python123.io/ws', headers=hd)
  • cookies:字典或CookieJar,指的是从http中解析cookie

  • auth:元组,用来支持http认证功能

  • files:字典, 是用来向服务器传输文件时使用的字段。

    例子:

    1
    2
    fs = {'files': open('data.txt', 'rb')} 
    r = requests.post('http://python123.io/ws', files=fs)
  • timeout: 用于设定超时时间, 单位为秒,当发起一个get请求时可以设置一个timeout时间, 如果在timeout时间内请求内容没有返回, 将产生一个timeout的异常。

  • proxies:字典, 用来设置访问代理服务器。

  • allow_redirects: 开关, 表示是否允许对url进行重定向, 默认为True

  • stream: 开关, 指是否对获取内容进行立即下载, 默认为True

  • verify:开关, 用于认证SSL证书, 默认为True

  • cert: 用于设置保存本地SSL证书路径

响应数据
属性说明
r.status_codehttp请求的返回状态,若为200则表示请求成功。
r.texthttp响应内容的字符串形式,即返回的页面内容
r.encodinghttp header 中猜测的相应内容编码方式
r.apparent_encoding从内容中分析出的响应内容编码方式(备选编码方式)
r.contenthttp响应内容的二进制形式
举例
1
2
3
4
5
6
7
8
9
10
11
12
13
14

import requests
r=requests.get("http://www.baidu.com")
r.status_code
200
r.encoding
'ISO-8859-1'
r.apparent_encoding
'utf-8'
r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>ipt> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a>&nbsp;京ICPè¯\x81030173å\x8f·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
r.encoding='utf-8'
r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta chref=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css="h读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'

request库异常

注意requests库有时会产生异常,比如网络连接错误、http错误异常、重定向异常、请求url超时异常等等。所以我们需要判断r.status_codes是否是200,在这里我们怎么样去捕捉异常呢?

这里我们可以利用r.raise_for_status() 语句去捕捉异常,该语句在方法内部判断r.status_code是否等于200,如果不等于,则抛出异常。

于是在这里我们有一个爬取网页的通用代码框架:

1
2
3
4
5
6
7
try:
r=requests.get(url,timeout=30)#请求超时时间为30秒
r.raise_for_status()#如果状态不是200,则引发异常
r.encoding=r.apparent_encoding #配置编码
return r.text
except:
return "产生异常"

request.head()

1
2
3
r=requests.head("http://httpbin.org/get")
r.headers
{'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Mon, 20 Nov 2017 08:08:46 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000658988952637', 'Content-Length': '268', 'Via': '1.1 vegur'}

requests.post()

post一个字典
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
payload={"key1":"value1","key2":"value2"}
r=requests.post("http://httpbin.org/post",data=payload)
print(r.text)
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "218.197.153.150",
"url": "http://httpbin.org/post"
}
post字符串
自动编码为data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
r=requests.post("URL地址",data='helloworld')
print(r.text)
{
"args": {},
"data": "helloworld",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "10",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "218.197.153.150",
"url": "URL地址"
}
post一个文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import requests
files = {'files':open('F:\\python\\test\\test_case\\files.txt','rb')}
r = requests.post('https://httpbin.org/post',files=files)
print(r.text)
{
"args":{

},
"data":"",
"files":{
"files":"hello worle!"
},
"form":{

},
"headers":{
"Accept":"*/*",
"Accept-Encoding":"gzip, deflate",
"Connection":"close",
"Content-Length":"158",
"Content-Type":"multipart/form-data; boundary=d2fb307f28aeb57b932d867f80f2f600",
"Host":"httpbin.org",
"User-Agent":"python-requests/2.19.1"
},
"json":null,
"origin":"113.65.2.187",
"url":"https://httpbin.org/post"
}

put和patch与post类似,故不再做示例。

requests代理

  • 什么是代理
    • 代理就是第三方代替本体处理相关事务。例如:生活中的代理:代购,中介,微商……
  • 爬虫中为什么需要使用代理
    • 一些网站会有相应的反爬虫措施,例如很多网站会检测某一段时间某个IP的访问次数,如果访问频率太快以至于看起来不像正常访客,它可能就会会禁止这个IP的访问。所以我们需要设置一些代理IP,每隔一段时间换一个代理IP,就算IP被禁止,依然可以换个IP继续爬取。
  • 代理的分类:
    • 正向代理:代理客户端获取数据。正向代理是为了保护客户端防止被追究责任。
    • 反向代理:代理服务器提供数据。反向代理是为了保护服务器或负责负载均衡。
  • 免费代理ip提供网站
    • http://www.goubanjia.com/
    • 西祠代理
    • 快代理

百度IP,测试是否代理ip成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import requests
import random
if __name__ == "__main__":
#不同浏览器的UA
header_list = [
# 遨游
{"user-agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)"},
# 火狐
{"user-agent": "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"},
# 谷歌
{
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"}
]
#不同的代理IP
proxy_list = [
{"http": "112.115.57.20:3128"},
{'http': '121.41.171.223:3128'}
]
#随机获取UA和代理IP
header = random.choice(header_list)
proxy = random.choice(proxy_list)

url = 'http://www.baidu.com/s?ie=UTF-8&wd=ip'
#参数3:设置代理
response = requests.get(url=url,headers=header,proxies=proxy)
response.encoding = 'utf-8'

with open('daili.html', 'wb') as fp:
fp.write(response.content)
#切换成原来的IP
requests.get(url, proxies={"http": ""})

会话维持

会话对象让你能够跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie, 简单的说,如果你要爬取的页面是登录后才能查看的网页,那么就要像浏览器访问一样,保持其登录状态,者就用到了session

登录人人网

登录人人网,如果有验证码要识别其验证码,登录后下载其个人主页页面。在这里着重说下验证码吧,很多网站登录都需要验证码,人人网也一样,可能是在你多次输入账号密码错误的时候才会让你填写验证码。关于识别验证码我们这里使用到了第三方的API,云打码,市面上有很多类似的产品,大概原理就是访问登录页面时,将页面上的验证码下载下来,使用第三方api识别然后进行登录,具体的第三方都会提供文档和示例代码,这里就不详细解释。

识别验证码文件

CodeDemo.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import http.client, mimetypes, urllib, json, time, requests

######################################################################

class YDMHttp:

apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''

def __init__(self, username, password, appid, appkey):
self.username = username
self.password = password
self.appid = str(appid)
self.appkey = appkey

def request(self, fields, files=[]):
response = self.post_url(self.apiurl, fields, files)
response = json.loads(response)
return response

def balance(self):
data = {'method': 'balance', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
response = self.request(data)
if (response):
if (response['ret'] and response['ret'] < 0):
return response['ret']
else:
return response['balance']
else:
return -9001

def login(self):
data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
response = self.request(data)
if (response):
if (response['ret'] and response['ret'] < 0):
return response['ret']
else:
return response['uid']
else:
return -9001

def upload(self, filename, codetype, timeout):
data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
file = {'file': filename}
response = self.request(data, file)
if (response):
if (response['ret'] and response['ret'] < 0):
return response['ret']
else:
return response['cid']
else:
return -9001

def result(self, cid):
data = {'method': 'result', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'cid': str(cid)}
response = self.request(data)
return response and response['text'] or ''

def decode(self, filename, codetype, timeout):
cid = self.upload(filename, codetype, timeout)
if (cid > 0):
for i in range(0, timeout):
result = self.result(cid)
if (result != ''):
return cid, result
else:
time.sleep(1)
return -3003, ''
else:
return cid, ''

def report(self, cid):
data = {'method': 'report', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'cid': str(cid), 'flag': '0'}
response = self.request(data)
if (response):
return response['ret']
else:
return -9001

def post_url(self, url, fields, files=[]):
for key in files:
files[key] = open(files[key], 'rb');
res = requests.post(url, files=files, data=fields)
return res.text

上述代码不用理解其意思,就是第三方给我们提供的示例,拿来可以直接使用

主代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import requests
from lxml import etree

from CodeDemo import YDMHttp

# 识别验证码
def captcha(username, password,appid,appkey, code_img='getcode.jpg', codetype=1004):
# 超时时间,秒
timeout = 60

# 检查
if (username == 'username'):
print('请设置好相关参数再测试')
else:
# 初始化
yundama = YDMHttp(username, password, appid, appkey)

# 登陆云打码
uid = yundama.login();
print('uid: %s' % uid)

# 查询余额
balance = yundama.balance();
print('balance: %s' % balance)

# 开始识别,图片路径,验证码类型ID,超时时间(秒),识别结果
cid, result = yundama.decode(code_img, codetype, timeout);
print('cid: %s, result: %s' % (cid, result))
# 此处应该做判断,如果识别不出来返回空
return result
# 要保持会话的页面我们使用session.get/post之类的就可以了
session = requests.session()
headers = {
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'
}
# 登录视图页面
login_view_url = "http://www.renren.com/"
# 获取登录视图源码
login_view = requests.get(url=login_view_url, headers=headers).text
tree = etree.HTML(login_view)
# 解析验证码图像地址
code_url = tree.xpath('//*[@id="verifyPic_login"]/@src')
# 验证码
code_num=None
# 判断验证码是否存在,存在则识别验证码,不存在则跳过识别
if code_url:
# 获取图片内容
code_img_content = requests.get(url=code_url[0], headers=headers).content
# 写入文件
with open('getcode.jpg', 'wb') as f:
f.write(code_img_content)
# 获取验证码软件id, 软件key
code_num = captcha(username = '云打码普通用户名', password = '云打码普通用户密码', appid = 9398, appkey = 'd34d4bc4bbbccf47f90f346d40a32aa2')

# 登录数据
# 登录数据这里是加密的,自己用浏览器登陆下,使用fiddler等抓包工具看下请求的数有哪些,并且看下加密后的密码
data={
'email' : '646547989@qq.com',
'icode':'',
'origURL':'http://www.renren.com/home',
'domain':'renren.com',
'key_id':'1',
'captcha_type':'web_login',
'password':'6196c549890d45f3495cd55dcd0bb1e883dbdb1578be1ede58ceb57381df0850',
'rkey':'088f9ddffb887cffe8956a6f85956689',
'f':''
}
#登录url
login_url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2019105950868'
# 登录网站
session.post(url=login_url, data=data, headers=headers)
# 个人主页
person_url = 'http://www.renren.com/858420730/profile'
# 访问个人主页
ret = session.get(url=person_url, headers=headers).content
# 下载个人主页
with open('renren.html', 'wb') as f:
f.write(ret)
print('可以了')

登录古诗文网

我们依然要用到识别验证码,上述代码中的识别验证码部分这里就不上了,直接主体部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import requests
from lxml import etree
# 导入云打码类
from CodeDemo import YDMHttp

# 识别验证码
def captcha(username, password,appid,appkey, code_img='getcode.jpg', codetype=1004):
# 超时时间,秒
timeout = 60

# 检查
if (username == 'username'):
print('请设置好相关参数再测试')
else:
# 初始化
yundama = YDMHttp(username, password, appid, appkey)

# 登陆云打码
uid = yundama.login();
print('uid: %s' % uid)

# 查询余额
balance = yundama.balance();
print('balance: %s' % balance)

# 开始识别,图片路径,验证码类型ID,超时时间(秒),识别结果
cid, result = yundama.decode(code_img, codetype, timeout);
print('cid: %s, result: %s' % (cid, result))
# 此处应该做判断,如果识别不出来返回空
return result

session = requests.session()
headers = {
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'
}
# 登录视图页面
login_view_url = "https://so.gushiwen.org/user/login.aspx"
# 获取登录视图源码
login_view = requests.get(url=login_view_url, headers=headers).text
tree = etree.HTML(login_view)
# 解析验证码图像地址
code_url = 'https://so.gushiwen.org/'+tree.xpath('//*[@id="imgCode"]/@src')[0]
code_num = None
# 判断验证码是否存在,存在则识别验证码,不存在则跳过识别
if code_url:
# 获取图片内容
code_img_content = session.get(url=code_url, headers=headers).content
with open('getcode.jpg', 'wb') as f:
f.write(code_img_content)
code_num = captcha(username = '云打码普通用户名', password = '云打码普通密码', appid = 9398, appkey = 'd34d4bc4bbbccf47f90f346d40a32aa2')


# 登录数据
# 同样使用抓包工具看下请求的数据都有哪些,__VIEWSTATE其实就是登陆表单中的表单令牌,密码呢这里没有先加密,填入你自己的密码就可以了
data={
'__VIEWSTATE' : 'yEtGeGM9HT6bkfg7wOcpOXeXOr9S95S6ZRAVjyb7gUkABub2sKT687x3F07JHTOYv6UFDTIj7nYLJsaScMl3Wq75yPUrbD3wbOhC8q+yNJDWFL3KKHRPPLwiz0E=',
'__VIEWSTATEGENERATOR': 'C93BE1AE',
'from': 'http://so.gushiwen.org/user/collect.aspx',
'email':'646547989@qq.com',
'pwd': '你的密码',
'code': code_num,
'denglu': '登录'
}
# 登陆请求地址
login_url = 'https://so.gushiwen.org/user/login.aspx'
# 登陆网站
session.post(url=login_url, data=data, headers=headers)

# 个人主页
person_url = 'https://so.gushiwen.org/user/collect.aspx'
# 访问个人收藏主页
ret = session.get(url=person_url, headers=headers).content

# 写入文件
with open('gsw.html', 'wb') as f:
f.write(ret)
print('可以了')

多线程

我们这里使用多线程爬取视频。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import  requests, re, time
from uuid import uuid4
from lxml import etree

from multiprocessing.dummy import Pool
#我的电脑8核的,我们这里就开一个8线程的线程池
pool = Pool(8)
url ='https://www.pearvideo.com/category_8'
headers = {
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'
}

res = requests.get(url=url, headers = headers).text

tree = etree.HTML(res)
# 获取视频详情链接
li_htmls = tree.xpath('//ul[@id="listvideoListUl"]/li/div/a/@href')

# 视频下载链接列表
video_url_lis=[]
# 解析视频下载链接
def get_video_url(video_detail_url):
video_detail = requests.get(url='https://www.pearvideo.com/{url}'.format(url=video_detail_url), headers=headers).text
video_url = re.findall('srcUrl="(.*?)",vdoUrl', video_detail, re.S)[0]
video_url_lis.append(video_url)

# 视频内容列表
video_content_lis=[]
def get_video_content(video_url):
video_content = requests.get(video_url, headers=headers).content
video_content_lis.append(video_content)

# 下载视频
def download_video(video_content):
filename= 'video/'+str(uuid4())+'.mp4'
with open(filename, 'wb') as f:
f.write(video_content)

start = time.time()
# 获取视频下载链接
pool.map(get_video_url, li_htmls)
print(video_url_lis)
# 获取视频内容
pool.map(get_video_content, video_url_lis)
# 下载视频
pool.map(download_video, video_content_lis)
end = time.time()
print('总用时:', end-start)

这里

爬取搜狗

请求载体身份标识的伪装:

  • User-Agent:请求载体身份标识,通过浏览器发起的请求,请求载体为浏览器,则该请求的User-Agent为浏览器的身份标识,使用爬虫程序发起的请求,则该请求的载体为爬虫程序,则该请求的User-Agent为爬虫程序的身份标识。可以通过判断该值来获知该请求的载体究竟是基于哪款浏览器还是基于爬虫程序。
  • 反爬机制:某些门户网站会对访问该网站的请求中的User-Agent进行捕获和判断,如果该请求的UA为爬虫程序,则拒绝向该请求提供数据。
  • 反反爬策略:将爬虫程序的UA伪装成某一款浏览器的身份标识。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import requests
import os
#指定搜索关键字
word = input('enter a word you want to search:')
#自定义请求头信息
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
#指定url
url = 'https://www.sogou.com/web'
#封装get请求参数
prams = {
'query':word,
'ie':'utf-8'
}
#发起请求
response = requests.get(url=url,params=param)

#获取响应数据
page_text = response.text

with open('./sougou.html','w',encoding='utf-8') as fp:
fp.write(page_text)

豆瓣电影排行榜

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import requests
import urllib.request
if __name__ == "__main__":

#指定ajax-get请求的url(通过抓包进行获取)
url = 'https://movie.douban.com/j/chart/top_list?'

#定制请求头信息,相关的头信息必须封装在字典结构中
headers = {
#定制请求头中的User-Agent参数,当然也可以定制请求头中其他的参数
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
}

#定制get请求携带的参数(从抓包工具中获取)
param = {
'type':'5',
'interval_id':'100:90',
'action':'',
'start':'0',
'limit':'20'
}
#发起get请求,获取响应对象
response = requests.get(url=url,headers=headers,params=param)

#获取响应内容:响应内容为json串
print(response.text)

豆瓣登录数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import requests
import os
url = 'https://accounts.douban.com/login'
#封装请求参数
data = {
"source": "movie",
"redir": "https://movie.douban.com/",
"form_email": "用户名",
"form_password": "密码",
"login": "登录",
}
#自定义请求头信息
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
response = requests.post(url=url,data=data)
page_text = response.text

with open('./douban111.html','w',encoding='utf-8') as fp:
fp.write(page_text)

药监局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import requests
from fake_useragent import UserAgent
# 随机设备标识,应对反爬虫
ua = UserAgent(use_cache_server=False,verify_ssl=False).random
headers = {
'User-Agent':ua
}

url = 'http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsList'
pageNum = 3
for page in range(3,5):
data = {
'on': 'true',
'page': str(page),
'pageSize': '15',
'productName':'',
'conditionType': '1',
'applyname':'',
'applysn':''
}
json_text = requests.post(url=url,data=data,headers=headers).json()
all_id_list = []
for dict in json_text['list']:
id = dict['ID']#用于二级页面数据获取
#下列详情信息可以在二级页面中获取
# name = dict['EPS_NAME']
# product = dict['PRODUCT_SN']
# man_name = dict['QF_MANAGER_NAME']
# d1 = dict['XC_DATE']
# d2 = dict['XK_DATE']
all_id_list.append(id)
#该url是一个ajax的post请求
post_url = 'http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsById'
for id in all_id_list:
post_data = {
'id':id
}
response = requests.post(url=post_url,data=post_data,headers=headers)
#该请求响应回来的数据有两个,一个是基于text,一个是基于json的,所以可以根据content-type,来获取指定的响应数据
if response.headers['Content-Type'] == 'application/json;charset=UTF-8':
#print(response.json())
#进行json解析
json_text = response.json()
print(json_text['businessPerson'])