爬虫常用基本库的初级用法和高级用法示例

学习python不久,但是还是想分享一些自己的想法或者思路,一起成长,下面是我的今日分享,希望大家持续关注,嘻嘻

两个基本库:urllib和requests。一、urllib的使用。

import urllib.request


response = urllib.request.urlopen('https://www.python.org')#获得HTTP response类型对象#print(response.read().decode('utf-8')) #网页源代码print(response.getheader('Server'))#获取响应头信息的Server值

from urllib import parse


url = 'http://httpbin.org/post'

headers = {

'User-Agent': 'Mozilla/4.0(compatible;MSIE 5.5;Windows NT)',

'Host':'httpbin.org'}#请求头,修改user-agent,伪装为浏览器dict = {

'name': 'Germey'}

data = bytes(parse.urlencode(dict),encoding='utf8')#转字流采用bytes方法

req = urllib.request.Request(url=url,data=data,headers=headers,method='POST')#返回Request类型对象

response = urllib.request.urlopen(req)print(response.read().decode('utf-8'))

#需要验证身份的网页from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener


username = 'username'

password = 'password'

url = 'http://localhost:5000/'


p = HTTPPasswordMgrWithDefaultRealm()

p.add_password(None,url,username,password) #利用add_password添加用户名及密码,建立处理验证的handler

auth_handler = HTTPBasicAuthHandler(p) #实例化HTTPBasicAuthHandler对象

opener = build_opener(auth_handler) #利用上述handler构建opener

try:

    result = opener.open(url) #利用opener发送请求,打开链接

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

    print(html)except urllib.error.URLError as a:

print('handler错误原因:'+str(a.reason))  #虚拟例子,肯定不能打开哈,我们在这里返回原因

#使用代理from urllib.request import ProxyHandler


proxy_handler = ProxyHandler({

'http':'http://127.0.0.1:9743',

'https':'https://127.0.0.1:9743'

})   #键名为协议类型,键值为代理链接,可添加多个连接,此代理运行在9743端口上

opener = build_opener(proxy_handler) #构造opener

try:    

    response = opener.open('https:baidu.com') #打开链接

    print(response.read().decode('utf-8'))except urllib.error.URLError as e:

print('代理错误原因:'+str(e.reason))

#cookies的处理import http.cookiejar


cookie = http.cookiejar.CookieJar()                  #声明Cookiejar对象

handler = urllib.request.HTTPCookieProcessor(cookie) #建立handler

opener = urllib.request.build_opener(handler)        #构建opener


response = opener.open('http://www.baidu.com')       #发送请求for item in cookie:

print(item.name+'='+item.value)

#输出为文件格式如下演示:

filename = 'cookie.txt'

cookie = http.cookiejar.MozillaCookieJar(filename)    #Cookiejar的子类,处理cookies和文件相关事务

handler = urllib.request.HTTPCookieProcessor(cookie) #建立handler

opener = urllib.request.build_opener(handler)        #构建opener

response = opener.open('http://www.baidu.com')       #发送请求

cookie.save(ignore_discard=True,ignore_expires=True)#第二种文件格式

filename = 'cookie_LWP.txt'

cookie = http.cookiejar.LWPCookieJar(filename)    #Cookiejar的子类,保存为libwww-perl(LWP)格式

handler = urllib.request.HTTPCookieProcessor(cookie) #建立handler

opener = urllib.request.build_opener(handler)        #构建opener

response = opener.open('http://www.baidu.com')       #发送请求

cookie.save(ignore_discard=True,ignore_expires=True)

#有效读取文件

filename = 'cookie_LWP.txt'

cookie = http.cookiejar.LWPCookieJar()    

cookie.load(filename,ignore_discard=True,ignore_expires=True)

handler = urllib.request.HTTPCookieProcessor(cookie) #建立handler

opener = urllib.request.build_opener(handler)        #构建opener

response = opener.open('http://www.baidu.com')       #发送请求#print(response.read().decode('utf-8'))        #获取百度网页的源代码

#解析链接,实现链接各部分的抽取,合并以及链接转换from urllib.parse import urlparse


result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')print(str('result的类型为:'),end='')print(type(result))print(result)      #6个部分,scheme协议,netloc域名,path访问路径,params参数,query查询条件,fragment锚点,定位页面内部的下拉位置

#urlprase的另一种用法


result = urlparse('www.baidu.com/index.html;user?id=5#comment',scheme = 'https')#注意,scheme参数只有在url中不包含scheme时才生效print(str('result的类型为:'),end='')print(type(result))print(result)

#对立方法urlunparse,接受可迭代对象,但参数长度必须为6from urllib.parse import urlunparse


data = ['https','www.baidu.com','index.html','user','a=6','comment']print(urlunparse(data))

#urlsplit与urlparse类似,但并不解析params部分,将其返回到path部分from urllib.parse import urlsplit


result = urlsplit('https://www.baidu.com/index.html;user?a=6#comment')print(result)#同样,urlsplit也有对立方法urlunsplit方法#urljoin方法,实现链接的更新,补充,双参数from urllib.parse import urljoin

print(urljoin('http://www.baidu.com/about.html','https://pangzixi.com/FAQ.html?question=2'))print(urljoin('http://www.baidu.com/about.html','http://www.baidu.com/about.html?question=2'))

#urlencode构造GET请求参数(序列化),及其反序列化from urllib.parse import urlencode,parse_qs,parse_qsl


params = {

'name':'germey',

'age':22}#首先声明一个字典,将参数表示出来

base_url = 'http://www.baidu.com?'

url =  base_url + urlencode(params) #调用urlencode方法,将其转化为请求参数print(str('序列化:')+str(url))

query = 'name=germey&age=22'print(str('反序列化:')+str(parse_qs(query)))print(str('反序列化(转化为元组列表):')+str(parse_qsl(query))) 

#quote方法,防止中文出现在url中时发生乱码现象from urllib.parse import quote,unquote


keyword = '张三'

url = 'http://www.baidu.com/s?wd=' + quote(keyword) #quote方法对中文进行UTF编码print(url)


url = 'http://www.baidu.com/s?wd=%E5%A3%81%E7%BA%B8' print(unquote(url)) #unquote实现解码


#分析Robots协议,协议规定爬虫或搜索引擎那些页面允许抓取,哪些不可以

'''

一般格式:

User-agent: *  对所有爬虫有效

Disallow: /    不允许爬取所有网页

Allow: /public/可以爬取public目录

'''

from urllib.robotparser import RobotFileParser


rp = RobotFileParser()#创建对象

rp.set_url('http://www.jianshu.com/robots.txt')#设置robots.txt链接

rp.read()#返回可读对象,另一种格式为:rp.parse(urlopen('http://www.jianshu.com/robots.txt').read().decode('utf-8').splite('\n'))print(rp.can_fetch('*','http://www.jianshu,com/p/b67554025d7d'))#查看是否允许抓取True/False

二、requests的使用,相较于urllib库,明显可以感觉requests的功能更强大而且方便。

#requests库能够更加方便的实现cookies以及登录验证,代理设置等import requests


r = requests.get('https://www.baidu.com/') #get方法发送请求print(r.cookies)print(r.status_code) #返回状态码

#GET请求

r = requests.get('http://httpbin.org/get')#print(r.text)

#附加额外信息

data = {

'name':'germey',

'age':32}

r = requests.get('http://httpbin.org/get',params=data)#print(r.text)

#网页的返回类型是str类型,是JSON格式,可直接调用json()方法

#print(r.json())

#抓取二进制数据

r = requests.get('https://www.github.com/favicon.ico')with open('favicon.ico','wb') as fn:

fn.write(r.content)  #保存二进制文件

#添加headers

headers = {

'User-Agent':'Mozilla/5.0(Macintosh;Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}

r = requests.get('https://www.zhihu.com/explore',headers=headers)#print(r.text)

#POST请求

r = requests.post('http://httpbin.org/post',data=data)#print(r.text)

#requests内置状态码查询对象if r.status_code!=requests.codes.ok:

exit()else:

print('Request Successfully')

#requests库的高级用法:文件上传,Cookies设置,代理设置#文件上传,以上传图片为例

files = {'file':open('favicon.ico','rb')}#保证py文件和ico文件在同一目录下,否则请填写绝对路径

r = requests.post('http://httpbin.org/post',files=files) #print(r.text)

#Cookies设置

r = requests.get('https://www.baidu.com')for key,value in r.cookies.items():

print(key + '=' + value)

#会话维持Session

s = requests.Session()

s.get('http://httpbin.org/cookies/set/number/123456')  #设置cookie的名称number,内容123456

r = s.get('http://httpbin.org/cookies') #获取该网页的cookiesprint(r.text)

#SSL证书验证from requests.packages import urllib3


urllib3.disable_warnings()#屏蔽指定证书的警告信息

response = requests.get('https://www.12306.cn',verify=False)#verify=False避免SSLError错误信息print(response.status_code)

#代理设置,针对大规模爬取可能出现的封IP现象#用到proxies参数


proxies = {

'http':'http://10.10.1.10:3128',

'https':'https://10.10.1.10:1080'}#一个例子,这是一个无效的代理


requests.get('https://www.taobao.com',proxies=proxies)

#超时设置timeout

r = requests('https://www.taobao.com',timeout=1)#1秒内无响应,就抛出异常#永久等待,可将timeout设置为None,或者不加timeout参数

#身份认证,遇到认证页面的操作

r = requests.get('http://lpcalhost:5000',auth=('username','password'))#username和password为举例说明,请输入你的真实信息以登录#或者采取OAuth1认证的方法,比较难受from requests_oauthlib import OAuth1


url = 'https://api.twitter.com/...'

auth = OAuth1('yourappkey','yourappsecret','useroauthtoken','useroauthtokensecret')

requests.get(url,auth)

#Prepared Request数据结构from requests import Request,Session


url = 'http://httpbin.org/post'

data = {'name':'germey'}

headers = {

'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36'}#此处复制百度页面的代理即可

s = Session()

request = Request('POST',url,data=data,headers=headers)

prepped = s.prepare_request(request)#封装Prepared Request对象

r = s.send(prepped) 

pint(r.text) 

版本为3.9.0。初入爬虫领域,欢迎交流评论。本人都是通过代码课堂学习的,大家可以一起来哦

http://www.daimaketang.com/course/explore/01A?subCategory=001A&orderBy=recommendedSeq,也希望大家多多提提意见呀。

你可能感兴趣的:(爬虫常用基本库的初级用法和高级用法示例)