Python爬虫02(urllib自带模块编写)

Python 3.x版本后的urllib和urllib2

现在的Python已经出到了3.5.2

在Python 3以后的版本中,urllib2这个模块已经不单独存在(也就是说当你import urllib2时,系统提示你没这个模块),urllib2被合并到了urllib中,叫做urllib.request 和 urllib.error 。

urllib整个模块分为urllib.request, urllib.parse, urllib.error。

例: 
其中urllib2.urlopen()变成了urllib.request.urlopen() 
urllib2.Request()变成了urllib.request.Request()

一.urllib模块的使用

1基本方法

urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)

-----url:需要打开的网址

-----data:Post提交的数据

-----timeout:设置网站的访问超时时间

直接用urllib.request模块的urlopen()获取页面,数据格式为bytes类型,需要decode()解码,转换成str类型。

import urllib.request

#向指定的url地址发送请求,并返回服务器响应的泪文件对象
response=urllib.request.urlopen(request)
#服务器返回的类文件对象支持python文件对象的操作方法
#read()方法就是读取文件里的全部内容,返回字符串
html=response.read()
html=html.decode('utf-8')

#返回http的响应码
print(response.getcode())
#返回实际数据的实际url,防止重定向问题
print(response.geturl())
#返回服务器相应的http报头
print(response.info())


#打印响应内容
print(html)

urlopen返回对象提供方法:

  • read(),readline(),readlines(),fileno(),close():对HTTPResponse类型数据进行操作
  • info():返回HTTPMessage对象,表示远程服务器返回的是头信息
  • getcode():返回http状态码,如果http请求,200请求成功完成;40wangzhiweizhaodao
  • geturl():返回请求的url

2.使用Request

urllib.request.Request(url,data=None,headers={},method=None)

使用request()来包装请求,再通过urlopen()获取页面

import urllib.request

#爬虫也反爬虫第一步
#构建基础的headers信息
ua_headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}
#通过urllib.request.Request()方法构造一个请求对象
request=urllib.request.Request("http://www.baidu.com/",headers=ua_headers)
#向指定的url地址发送请求,并返回服务器响应的泪文件对象
response=urllib.request.urlopen(request)
#服务器返回的类文件对象支持python文件对象的操作方法
#read()方法就是读取文件里的全部内容,返回字符串
html=response.read()

html=html.decode('utf-8')

#打印响应内容
print(html)

用来包装头部的数据:

- Usr-Agent:这个投不可以携带如下几条信息:浏览器名和版本号,操作系统名和版本号,默认语言

-  Referer:可以用来放到连接,有一些网站图片现实来源http://***.com,就是检测Referer来鉴定的

- Connection:表示连接状态,记录Session的状态

3.Post数据

urlopen()的data参数默认为None,当data参数不为空的时候,urlopen()提交方式为Post

#usr/bin/python
#-*-coding:utf-8-*-
import urllib.request


from urllib import parse

ua_headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}

data={
    'first':'true',
    'pn':1,
    'kd':'Python'
}
data=parse.urlencode(data).encode('utf-8')
request=urllib.request.Request("http://www.lagou.com/jobs/positionAjax.json?",headers=ua_headers,data=data)


response=urllib.request.urlopen(request)

html=response.read()

html=html.decode('utf-8')

#打印响应内容
print(html)

urllib.parse.urlencode()主要作用是将url附上要提交的数据

经过urlencode()转换后的data数据为?first=true?pn=1?kd=Python,最后提交的url为

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

4.Python 3中urlencode模块的使用

urlencode方法所在位置 

urllib.parse.urlencode(values)

字符的编码翻译

from urllib import parse

wd={'wd':'欢迎你'}
print(parse.urlencode(wd))

输出

使用

#usr/bin/python
#-*-coding:utf-8-*-
import urllib.request
from urllib import parse

url="http://www.baidu.com/s"
keyword=input("请输入需要查询的字符串:")
wd={"wd":keyword}
headers={"User-Agent": "Mozilla...."}
#通过parse.urlencode()参数是一个dict类型
wd=parse.urlencode(wd)
#拼接完整的url
fullurl=url+"?"+wd
#构建请求
request=urllib.request.Request(fullurl,headers=headers)
response=urllib.request.urlopen(request)

print(response.read().decode('utf-8'))

例子:简单的贴吧爬取,并保存在本地

#usr/bin/python
#-*-coding:utf-8-*-
import urllib
from urllib import request,parse

def loadPage(url,filename):
    '''
    作用:根据url发送请求,获取服务器响应群文件
    url:需要爬取的url地址
    :return:
    '''
    print("正在下载"+filename)
    headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
    request=urllib.request.Request(url,headers=headers)
    return urllib.request.urlopen(request).read()

def writePage(html,filename):
    '''
    作用:将html内容写入到本地
    html:服务器相应文件内容
    :param html:
    :return:
    '''
    print("正在保存"+filename)
    #文件写入操作   不需要做文件关闭操作,不需要做上下文操作
    with open(filename,"w") as f:
        f.write(str(html))
    print("保存完成")
    print("-"*30)
    
def tiebaSpider(url,beginPage,endPage):
    '''
    作用:贴吧爬虫调度器,负责组合处理每个页面的url
    url:贴吧的url前部分
    beginPage:起始页
    endPage:结束页
    :return:
    '''
    for page in range(beginPage,endPage+1):
        pn=(page-1)*50
        filename="第"+str(page)+"页.html"
        fullurl=url+"&pn="+str(pn)
        # print (fullurl)
        html=loadPage(fullurl,filename)
        # print(html)
        writePage(html,filename)
    print("谢谢使用")
if __name__=="__main__":
    kw=input("请输入需要爬取的贴吧名:")
    beginPage=int(input("请输入起始页:"))
    endPage=int(input("请输入结束页:"))

    url="http://tieba.baidu.com/f?"
    key=parse.urlencode({"kw":kw})
    fullurl=url+key
    tiebaSpider(fullurl,beginPage,endPage)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章