今天开始学习python网络爬虫,写个博客作为笔记以及自己的学习过程以监督自己。
今天学习了urllib这个python包的一部分内容,主要是urllib.request
内容简记:
urllib.request.urlopen()详解
利用以上最基本的urlopen()方法,我们可以完成最基本的简单网页的GET请求抓取。data参数
data参数是可选的,如果要添加data,它要是字节流编码格式的内容,即bytes类型,通过bytes()函数可以进行转化,另外如果你传递了这个data参数,它的请求方式就不再是GET方式请求,而是POST。timeout参数
timeout参数可以设置超时时间,单位为秒,意思就是如果请求超出了设置的这个时间还没有得到响应,就会抛出异常,如果不指定,就会使用全局默认时间。它支持HTTP、HTTPS、FTP请求。
自作练习(简单的把样例代码自己敲一遍):
练习1简单爬网页元素
import urllib.request
import urllib.parse
import urllib.error
import socket
response = urllib.request.urlopen('https://www.python.org')
print(response.read().decode('utf-8'))
print(type(response))
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
练习2urlopen函数data参数
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
response = urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read())
input()
练习3 urlopen函数timeout参数
response = urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(response.read())
练习4 捕获timeout异常
try:
response = urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
pass
except Exception as e:
if isinstance(e.reason,socket.timeout):
print('TIME OUT!')
pass
pass
今天挺忙的只敲了这些,之前写python不多,敲得有些生疏