标签:htm from request content user proxy span on() 表单
下载安装:pip install requests
#requests模块 import requests #发送请求 content:以二进制的形式获取网页的内容 response=requests.get("http://www.baidu.com").content.decode() #response=requests.request("get","http://www.baidu.com").content.decode() print(response)
import requests url="http://www.baidu.com/s?" headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" } wd={"wd":"中国"} response=requests.get(url,params=wd,headers=headers) # 返回一个字符串形式的数据 data=response.text # 返回一个二进制形式的数据 data2=response.content print(data2.decode())
处理get请求:get()方法
处理post请求:post()方法
import requests import re #构造请求头信息 header={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36" }#谷歌浏览器 #http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule 网页上的url url="http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule" key="靓仔" #发送到web服务器的表单数据 formdata={ "i":key, "from":"AUTO", "to":"AUTO", "smartresult":"dict", "client":"fanyideskweb", "salt":"15880563488791", "sign":"cc2c40d740538fc5edc0380891faef27", "ts":"1588053583943", "bv":"f9c86b1fdf2f53c1fefaef343285247b", "doctype":"json", "version":"2.1", "keyfrom":"fanyi.web", "action":"FY_BY_REALTlME" } response=requests.post(url,headers=header,data=formdata) # 获取到的是json数据 # 对应的是字典 # print(response.json()) pat=r‘"tgt":"(.*?)"}]]‘ #字符串中有"",再用‘‘括起来表示字符串 # 获取到的是字符串 result=re.findall(pat,response.text) print(result[0])
import requests #设置ip地址 #proxy={"http":"http://代理ip地址:端口号"} #可以设置多个 proxy={ "http":"http://222.82.130.23:8060", "http":"http://101.248.64.68:80", } response=requests.get("http://www.baidu.com",proxies=proxy) print(response.content.decode())
cookie:用户信息
import requests response=requests.get("http://www.baidu.com") #1.获取返回的cooketjar对象 cookiejar=response.cookies #2.将cookiejar转换成字典 cookiedict=requests.utils.dict_from_cookiejar(cookiejar) print(cookiedict)
相比直接使用cookie,创建session可以得到新的cookie信息,不会出现cookie失效的情况
#使用session实现登陆 import requests #构造请求头信息 header={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36" }#谷歌浏览器 #创建session对象 ses=requests.session() #构造登陆需要的参数 data={"email":"325*****@qq.com","password":"123321a"} #通过传递用户名密码得到cookie信息 ses.post("http://www.renren.com/PLogin.do",data=data,headers=header) #请求需要的页面,每次请求会带入cookie信息 response=ses.get("http://www.renren.com/880151247/profile") print(response.text)
标签:htm from request content user proxy span on() 表单
原文地址:https://www.cnblogs.com/Just-a-calm-programmer/p/12956945.html