【python爬虫】request模块学习

主要利用 requests 库。

文章目录

  • (1)get请求
  • (2)Response对象属性
  • (3)post请求

(1)get请求



import requests

url = 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=38785274,1357847304&fm=26&gp=0.jpg'
headers = {'User-Agent':'Mozilla/4.0'}
# 设置代理,好像网站使用的协议
proxies = {'http':'http://127.0.0.1:808'}  

html = requests.get(url,headers =headers,proxies=proxies).content

with open('D:/1.jpg','wb') as f:
    f.write(html)


(2)Response对象属性

通过requests.get/post等方法返回值是 一个 response对象

encoding	查看或者指定响应字符编码
status_code	返回HTTP响应码
url	查看请求的 url 地址
headers	查看请求头信息
cookies	查看cookies 信息
text	以字符串形式输出
content	以字节流形式输出,若要保存下载图片需使用该属性

(3)post请求

和get请求大致相同,多了一个请求体 需要data 。

url = ''
headers = {'User-Agent':'User-Agent:Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11'}
parm1 = {
    'name':'编程帮'
}

data1 = {
    'from':'zh',
    'to':'en',
    'query':'编程帮www.biancheng.net你好'
}
response2 = requests.post(url=url, data=data1)




总结:
利用requests库时使用的代理为proxies参数,类型为字典;
post请求需要设置 data参数;
打开超文本open的模式使用b二进制模式;
实际编码需要利用好response属性,做好逻辑判断。

你可能感兴趣的:(python,python,爬虫,学习)