requests模块高级
cookie
import requests
#生成一个session对象
session = requests.session()
#1 发起登录请求:将cookie获取,且存储到session对象中
login_url='https://accounts.douban.com/login'
data={
'source':'movie',
'redir':'https://movie.douban.com/',
'form_email':'15027900535',
'form_password':'bobo@15027900535',
'login':'登录'
}
# 自定义请求头信息
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}
# 使用session发起post请求
login_response = session.post(url=login_url,data=data,headers=headers)
#2 对个人主页发起请求(session(cookie)),获取响应页面数据
url = 'https://www.douban.com/people/185687620/'
response = session.get(url=url,headers=headers)
page_text = response.text
with open('./douban110.html','w',encoding='utf-8')as fp:
fp.write(page_text)
代理操作
import requests
url = 'http://www.baidu.com/s?wd=ip&ie=utf-8' #协议要和代理IP统一
# 将代理IP封装到字典
proxies={
'http':'59.44.43.198:80'
}
# 更换IP
response = requests.get(url=url,proxies=proxies)
with open('./daili.html','w',encoding='utf-8')as fp:
fp.write(response.text)
print('ok')