day1记录-python爬虫urllib

之前打过一点基础(并不牢靠) 跟着 《解析python网络爬虫:核心技术……》过一遍
我感觉这些我上课好像都听过一点 我彷佛没有上过课sad
————

1.urllib的四大模块:

request error robotparser parser

2.得到一个request对象

request = urllib.request.Request(url)

3.得到一个响应

response = urllib.request.urlopen(url)
或者 response = urllib.request.urlopen(request)

**urlopen()方法的定义格式(书p44)
参数有:url:表示地址的字符串 或者request对象 data:bytes对象 设置data时,请求方式为post timeout

4.读取网页内容

html = response.read().decode(’’)

import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
#html = response.read().decode('utf-8')
print(response)

得到:<http.client.HTTPResponse object at 0x0372AC30>

Q:为什么不能直接print(response)
响应和响应’内容’的区别是啥?

A:得到的响应封装在了httpResponse类型的对象中,response这个封装了响应的对象,返回文件对象拥有获取url,状态码,内容等一系列方法。

5.response对象的一些方法(类提供的方法)
print(response.geturl())#1.响应内容的网址
print(response.getcode())#2.响应状态码
print(response.info()) #3.返回页面元信息
6.url编码转换

将键值对(字典)转换为字符串
urllib.parse.urlencode(data)
解码
urllib.parse.unquote(‘a=%E…’)

import urllib.parse
data ={
    'a':'啊哈',
    'b':'哎嘿'
}
result =urllib.parse.urlencode(data)
print(result)
result2 = urllib.parse.unquote('a=%E5%95%8A%E5%93%88&b=%E5%93%8E%E5%98%BF')
print(result2)
7.关于headers
  • 增加/修改一个特定的header --request.add_header(‘key’,‘value’)
  • 查看某个header信息 --request.get_header(header_name=‘key’)
request.add_header('Connection','keep-alive')
print(request.get_header(header_name='Connection'))
8.代理服务器
  • 自定义opener

构建处理器对象:http_handler = urllib.request.HTTPHandler()
创建opener对象 :opener = urllib.request.build_opener(http_handler)
发送request请求 :response = opener.open(request)

  • 代理服务器

httpproxy_handler = urllib.request.ProxyHandler({})

9.网络异常
  • URLError: urllib.error.URLError
  • HTTPError:urllib.error.HTTPError

用try ……except……结构

**页面元信息:元信息是关于信息的信息,用于描述信息的结构、语义、用途和用法等。元信息允许服务器提供所发送数据的信息。 html的元信息其实就是meta标签,标签位于文档的头部,不包含任何内容。
**打开DebugLog 自动打印收包和发包的报头

————

第三方库requests.
1.三种常用的类:Request/Response/Session
2.requests库的请求函数
  • .request() 构造一个请求
  • .get() 获取网页 http get请求方式
  • .head() 获取网页头信息的方法 HTTP HEAD请求方式
  • .post() 提交post请求的方法
  • .put() 提交put请求的方法
  • .patch() 提交局部修改请求
  • .delete() 提交删除请求
3.response类的常用属性
  • status.code 响应码
  • text 响应内容的字符串形式
  • encoding 猜测的编码方式
  • apparent_encoding 分析的编码方式
  • content 响应内容的二进制形式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值