python爬虫学习之urllib库

urlopen

  1. get类型的网页:
    import urllib.request
     response = urllib.request.urlopen("http://www.baidu.com")
     print(response.read().decode('utf-8'))

     

  2. post类型的网页:
    import urllib.request
    import urllib.parse
    data=bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
    response = urllib.request.urlopen("http://httpbin.org/post",data=data)#做http测试的网址
    print(response.read())

     

  3.  超时

    import urllib.request
    
    response = urllib.request.urlopen("http://httpbin.org/get",timeout=1)
    print(response.read())
    
    import socket
    import urllib.request
    import urllib.error
    try:
        response=urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
    except urllib.error.URLError as e:
        if isinstance(e.reason,socket.timeout):
            print("TIME OUT")

     

 

响应

状态码、响应头

import socket
import urllib.request
import urllib.error
try:
    response=urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print("TIME OUT")

 Request

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

     

    from urllib import request,parse
    url = "http://httpbin.org/post"
    headers = {
        'User-Agent':'Mozilla/4.0(compatible;MSIE ;Windows NT)',
        'Host':'httpbin.org'
    }
    dict = {
        'name':'Germey'
    }
    data  = bytes(parse.urlencode(dict),encoding='utf-8')
    req = request.Request(url=url,data=data,headers=headers,method='POST')
    response = request.urlopen(req)
    print(response.read().decode('utf-8'))
    
    也可以写成
    
    from urllib import request,parse
    url = "http://httpbin.org/post"
    dict = {
        'name':'Germey'
    }
    data  = bytes(parse.urlencode(dict),encoding='utf-8')
    req = request.Request(url=url,data=data,method='POST')
    req.add_header( 'User-Agent','Mozilla/4.0(compatible;MSIE ;Windows NT)')
    response = request.urlopen(req)
    print(response.read().decode('utf-8'))

     

 

 Handler 

  1. 代理
    import urllib.request
    proxy_handler = urllib.request.ProxyHandler({
        'http':'http://127.0.0.1:9743',
        'https':'https://127.0.0.1:9743' #代理网址
    })
    opener = urllib.request.build_opener(proxy_handler)
    response = opener.open("http://www.baidu.com")
    print(response.read())

     

cookie(检查-application) 

import http.cookiejar,urllib.request

cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener =urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com")
for item in cookie:
    print(item.name+"="+item.value)

存储 

import http.cookiejar,urllib.request
filename = 'cookie.txt'
cookie =http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener =urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com")
cookie.save(ignore_discard=True,ignore_expires=True)

 读取

import http.cookiejar,urllib.request
cookie = http.cookiejar.MozillaCookieJar()
cookie.load('cookie.txt',ignore_discard=True,ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com")
print(response.read().decode('utf-8'))

异常处理

from urllib import request,error
try:
    response = request.urlopen("http://www.cuiqingcai.com/index.htm")
except error.URLError as e:
    print(e.reason)

好的写法:

from urllib import request,error

try:
    response = request.urlopen("http://cuiqingcai.com/index.htm")
except error.HTTPError as e: #先捕捉子类异常
    print(e.reason,e.code,e.headers,sep='\n')
except error.URLError as e:  #后捕捉父类异常
    print(e.reason)
else :
    print("Request Successfully")
import socket
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://www.baidu.com',timeout=0.01)
except urllib.error.URLError as e:
    print(type(e.reason))
    if isinstance(e.reason,socket.timeout):
        print("TIME OUT")

URL解析

  1. urlparse
    from urllib.parse import urlparse
    
    result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
    result = urlparse('www.baidu.com/index.html;user?id=5#comment',scheme='https')# scheme为https
    result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',scheme='https') #scheme仍为http
    result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',allow_fragments=False)# fragment会拼接到query上
    result = urlparse('http://www.baidu.com/index.html#comment',allow_fragments=False)# fragment会拼接到params上
    print(type(result),result)
    
    

     

  2. urlunparse

    from urllib.parse import urlunparse
    
    data = ['http','www.baidu.com','index.html','user','a=6','comment']
    print(urlunparse(data))

     

  3. urljoin

    from urllib.parse import urljoin
    
    print(urljoin('http://www.baidu.com','FAQ.html'))#此类可以连接,如果两个都是http(s)开头那么会覆盖
    

     

  4. urlencode

    from urllib.parse import urlencode
    
    params = {
        'name':'gemey',
        'age':22
    }
    base_url = "http://www.baidu.com?"
    
    url = base_url + urlencode(params)
    print(url)

     

 

 

 

 

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