在简略爬虫中,第二个步骤就是应用网页下载器对网页进行下载以及获取下载申请的状态等。urllib2 库次要用于读取网页内容以及申请状态、cookielib 库次要为了减少网页下载器解决 cookie 的能力。
1、导入第三方扩大库
1# 导入 urllib2 库、用于网页下载 2import urllib2 3# 导入 cookielib 库、解决 cookie 信息 4import cookielib
2、urlopen() 函数实现网页下载
1def use_urlopen(url): 2 if url is None: 3 # 定义爬虫的 url 4 url = "http://www.baidu.com" 5 # 关上网页下载链接 6 response = urllib2.urlopen(url) 7 # 打印申请的响应状态,200 时示意胜利 8 print "网页申请状态:", response.getcode() 9 # read() 读取网页源代码内容 10 content = response.read() 11 # 打印源代码内容 12 print "源代码内容:", content 13 # 获取源代码内容的字符串长度 14 print "网页字符串长度:", len(content)
3、Request() 函数模仿浏览器实现网页下载
1def use_request(url): 2 if url is None: 3 # 定义爬虫的 url 4 url = "http://www.baidu.com" 5 # 结构 request 申请 6 request = urllib2.Request(url) 7 # 增加结构申请头 8 request.add_header("user-agent", "Mozilla/5.0") 9 # 关上网页下载链接 10 response = urllib2.urlopen(request) 11 # 打印申请的响应状态,200 时示意胜利 12 print "网页申请状态:", response.getcode() 13 # read() 读取网页源代码内容 14 content = response.read() 15 # 打印源代码内容 16 print "源代码内容:", content 17 # 获取源代码内容的字符串长度 18 print "网页字符串长度:", len(content)
4、build_opener() 函数退出网页下载器解决 cookie 的能力
1def use_build_opener(url): 2 if url is None: 3 # 定义爬虫的 url 4 url = "http://www.baidu.com" 5 # 获取 cookie 对象 6 cookie = cookielib.CookieJar() 7 # 将 cookie 解决能力退出 opener 8 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) 9 # 装置 opener 10 urllib2.install_opener(opener) 11 # 关上下载链接 12 response = urllib2.urlopen(url) 13 # 打印申请的响应状态,200 时示意胜利 14 print "网页申请状态:", response.getcode() 15 # read() 读取网页源代码内容 16 content = response.read() 17 # 打印源代码内容 18 print "源代码内容:", content 19 # 获取源代码内容的字符串长度 20 print "网页字符串长度:", len(content) 21 # 打印 cookie 信息 22 print "cookie 信息",cookie
实力的晋升是最重要的,进入公众号回复:“python计算题”,支付100道 python 案例计算题、快去支付刷题吧~
更多精彩返回微信公众号【Python 集中营】,关注获取《python 从入门到精通全套视频》