Python之requests模块--淘宝搜索为登录前的数据抓取为例

一、安装

pip install requests

如果报错:

方法一:cmd 切换到Python安装路径中的Scripts下   输入  pip install  ;

方法二:配置Scripts目录的环境变量

二、发送get,post请求,获取响应

requests.get(url) #发送get请求,请求url对应的响应

import requests;
url="http://www.baidu.com";
response=requests.get(url);
print(response);

 

response =requests.post(url,data={请求体的字典}) #发送post请求

#coding=utf-8
import requests;
url="http://fanyi.baidu.com/basetrans"
query={"query":"人生苦短",
       'form':'zh',
       'to':'en'}
response=requests.post(url,data=query)
print(response)

前面两种请求的执行结果

Python之requests模块--淘宝搜索为登录前的数据抓取为例_第1张图片

 

三、response方法

response.text 该方式往往出现乱码,出现乱码使用  response.encoding='utf-8'

response.content.decode()把响应的二进制字节流转化为str类型

response.request.url 发送请求的url地址

response.url #respons响应的url

response.request.headers #请求头

response.headers #响应请求

四、获取网页源码的正确打开方式

1.response.content.decode()

2.response.content.decode('gbk')

3.respons.text

 

Python之requests模块--淘宝搜索为登录前的数据抓取为例_第2张图片

五、发送带header的请求(为了模拟浏览器,获取和浏览器一模一样的内容)

headers={
   " User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"
}

response=requests.get(url,headers=headers);

 六、爱淘宝为例请求搜索的数据

#encoding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import requests;
headers={
   "user-agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36"
}
url="https://ai.taobao.com/search/getItem.htm?_tb_token_=503e39f39b83e&__ajax__=1&pid=mm_10011550_0_0&unid=&clk1=&page=2&pageSize=60&pvid=200_11.8.64.128_366_1557394562373&squareFlag=&sourceId=search&ppathName=&supportCod=&city=&ppath=&dc12=&pageNav=false&itemAssurance=&fcatName=&price=&cat=&from=&tmall=&key=爵士舞蹈服装&fcat=&ppage=0&debug=false&sort=&exchange7=&custAssurance=&postFree=&npx=50&location=&personalizeSwitch=";
response=requests.get(url,headers=headers);
print(response.content.decode());

执行结果

Python之requests模块--淘宝搜索为登录前的数据抓取为例_第3张图片

七、使用超时参数

requests.get(url,headers=headers,timeout=3)#3秒之内返回响应,否则会报错

 

你可能感兴趣的:(python)