1、get请求
"""
urllib
(1)一个类型以及六个方法
(2) get请求
(3) post请求―百度翻译
(4) ajax的get请求
(5) ajax的post请求
(6) cookie登陆 微博
(7) 代理
#requests
(1)一个类型以及六个特性
(2)get请求
(3)post请求
(4)代理
(5)cookie 验证码
"""
import requests
url = 'https://www.baidu.com/s?'
headers = {
'headers' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
}
data = {
'wd':'北京'
}
response = requests.get(url=url,params=data,headers=headers)
content = response.text
print(content)
"""
(1)参数使用params传递
(2)参数无需urlencode编码
(3)不需要请求对象的定制
(4)请求资源路径中的?可以加也可以不加
"""
2、post请求
import requests
url = 'https://fanyi.baidu.com/sug'
headers = {
'headers' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
}
data = {
'kw' : 'eye'
}
"""
url 请求地址
data 请求参数
kwargs 字典
"""
response = requests.post(url=url,data=data,headers=headers)
content = response.text
import json
obj = json.loads(content,encoding = 'utf-8')
print(obj)
"""
总结:
(1)post 请求 是不需要编解码
(2)post请求的参数是data
(3)不需要请求对象的定制
"""
3、requests代理
import requests
url = 'https://www.baidu.com/s?'
headers = {
'headers' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
}
data = {
'wd':'ip'
}
proxy = {
'http':'212.129.251.55:16816'
}
response = requests.get(url=url,params=data,headers=headers,proxies=proxy)
content = response.text
with open('daili.html','w',encoding='utf-8')as fp:
fp.write(content)
4、cookies登录
"""
难点:
(1)__VIEWSTATE __VIEWSTATEGENERATOR 一般情况下看不到数据 都是在页面的源码中
我们观察到这两个数据都是在页面的源码中 所以我们需要获取页面的源码 然后进行解析就可以了
(2)验证码
"""
import requests
url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
headers = {
'headers' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
}
response = requests.get(url = url,headers=headers)
content = response.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(content,'lxml')
viewstate = soup.select('#__VIEWSTATE')[0].attrs.get('value')
viewstategenerator = soup.select('#__VIEWSTATEGENERATOR')[0].attrs.get('value')
code = soup.select('#imgCode')[0].attrs.get('src')
code_url = 'https://so.gushiwen.cn' + code
session = requests.session()
response_code = session.get(code_url)
content_code = response_code.content
with open('code.jpg','wb')as fp:
fp.write(content_code)
code_name = input('请输入你的验证码:')
url_post = 'https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'
data_post = {
'__VIEWSTATE': 'viewstate',
'__VIEWSTATEGENERATOR': 'viewstategenerator',
'from': 'http://so.gushiwen.cn/user/collect.aspx',
'email': '18392118151',
'pwd': 'xpt666',
'code': 'code_name',
'denglu': '登录'
}
response_post = session.post(url=url,headers=headers,data = data_post)
content_post = response_post.text
with open('gushiwen.html','w',encoding='utf-8')as fp:
fp.write(content_post)