HTML
最简单的html
新建一个文本文件,后缀名是.html
这就是一个最简单的 HTML 实例 开头用 DOCTYPE 定义了文档类型,其次最外层是 html 标签,
段后还有对应的结束标签来表示闭合,其内部是 head 签和 body 标签,分别代表网页头和网页体,
它们也需要结束标签 head 标签内定义了一些页面的配置和引用,如:
爬取python官网
import urllib.request
response= urllib.request.urlopen( ' https://www.python.org')
print(response. read(). decode (’ utf-8'))
以上2行代码就可以直接爬取python官网的代码 ,下面我们来看看趴下来的东西的类型
import urllib.request
response = urllib.request.urlopen (’ https://www.python.org')
print(type(response))
结果如下:
<class ’ http.client.HTTPResponse ’ >
import urllib.request
response = urllib .request . urlopen (’ https://www . python.org ’)
print(response .status)
print(response .getheaders())
print(response .getheader (' Server'))
运行结果如下
200
和
[('Server ', ’ nginx'), ('Content-Type ', ’text/html; charset=utf-8'), (’ X-Frame-Option s ’,’ SAMEORIGIN'),
(’X-Clacks-Overhead t ,’GNU Terry Pratchett ’) , ('Content- Length ’ 3 ’47397 ' ), (’ Accept-Ranges’, t bytes’),
(’ Date', 'Mon, 01Aug201609:57:31GMT'), (’Via ’,’ 1.1 varnish ’),(‘ Age ’,’ 2473 ‘),(’ Conn ect ion' ,’ close'),
(’ X-Served-By ’,’ cache-lcy112s-LCY ' ), (' X-Cache ’,’HIT'), (’ X-Cache-Hits ',’ 23')' (’ Vary ’,'Cookie' ),
('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
和
nginx
可见,前两个输出分别输出了响应的状态码和响应的头信息,最后一个输出通过调用 getheade r()
方法并传递 个参数 Server 获取了响应头中的 Server 值,结果是 nginx ,意思是服务器是用 Ngin搭建的
利用最基本的 urlopen ()方法,可以完成最基本的简单网页的 GET 请求抓取
如果想给链接传递一些参数,该怎么实现呢?首先看一下 urlopen ()函数的 API:
urllib . request . urlopen(url, data=None, [ timeout, ]*, cafile=None, capath=None, cadefault=False, context=None )
可以发现,除了第一个参数可以传递 URL 之外,我们还可以传递其他内容,比如 data (附加数据)、 timeout (超时时间)
data 参数
data 参数是可选的 如果要添加该参数,并且如果它是字节流编码格式的内容,即 bytes 类型,
则需要通过 bytes ()方法转化 另外,如果传递了这个参数,则它的请求方式就不再是 GET 方式,而是POST方式
下面用实例来看 下:
import urllib.parse
import urllib.request
data = bytes(urllib . parse . urlencode({‘word ’:’ hello’}), encoding =’ utf8’)
response= urllib.request.urlopen('http://httpbin.org/post ’, data=data)
print(response.read())
这里我们传递了一个参数 word ,值是 hello 它需要被转码成 bytes (字节流)类型 其中转字节流采用了 bytes ()方法,该方法的第一个参数需要是 str (字符串)类型,需要用 urllib.parse模块里的 ur lencode ()方法来将参数字典转化为字符串;第 个参数指定编码格式,这里指定为 utf8
这里请求的站点是 httpbin .org ,它可以提供 HTTP 请求测试 本次我们请求的 URL为 http : // httpbin.org/ post ,这个链接可以用来测试 POST 请求,它可以输出请求的一些信息 ,其中包含我们传递的 data参数
运行结果如下:
{
“args” : {},
”data ”:,
"files”:{},
”form ”: { “ word ":”hello” },
"headers ": {
“ Accept-Encoding “:”identity”, “ Content-Length”: '’ 10”,
”Conten-type": “application/x-www-form -urlencoded”,
“Host ”:” httpbin.org ”,
”User-Agent”:”Python-urllib/3. 5”
},
’’ json ”: null ,
”origin ":” 123.124.23.253 ”,
“url”:”http://httpbin.org/post”
}
我们传递的参数州现在了 form 字段中,这表明是模拟了表单提交的方式,以 POST 方式传输数据