zoukankan      html  css  js  c++  java
  • Python3中urllib使用介绍

    Py2.x:

    • Urllib
    • Urllin2

    Py3.x:

    • Urllib

    变化:

    • 在Pytho2.x中使用import urllib2——-对应的,在Python3.x中会使用import urllib.requesturllib.error
    • 在Pytho2.x中使用import urllib——-对应的,在Python3.x中会使用import urllib.requesturllib.errorurllib.parse
    • 在Pytho2.x中使用import urlparse——-对应的,在Python3.x中会使用import urllib.parse
    • 在Pytho2.x中使用import urlopen——-对应的,在Python3.x中会使用import urllib.request.urlopen
    • 在Pytho2.x中使用import urlencode——-对应的,在Python3.x中会使用import urllib.parse.urlencode
    • 在Pytho2.x中使用import urllib.quote——-对应的,在Python3.x中会使用import urllib.request.quote
    • 在Pytho2.x中使用cookielib.CookieJar——-对应的,在Python3.x中会使用http.CookieJar
    • 在Pytho2.x中使用urllib2.Request——-对应的,在Python3.x中会使用urllib.request.Request

    快速爬取一个网页

    import urllib.request
    
    file=urllib.request.urlopen('http://www.baidu.com')
    
    data=file.read()    #读取全部
    
    dataline=file.readline()    #读取一行内容
    
    fhandle=open("./1.html","wb")    #将爬取的网页保存在本地
    fhandle.write(data)
    fhandle.close()

    浏览器的模拟

    应用场景:有些网页为了防止别人恶意采集其信息所以进行了一些反爬虫的设置,而我们又想进行爬取。 
    解决方法:设置一些Headers信息(User-Agent),模拟成浏览器去访问这些网站。

    import urllib.request
    import urllib.parse
    
    url = 'http://www.baidu.com'
    header = {
       'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36'
    }
    
    request = urllib.request.Request(url, headers=header)
    reponse = urllib.request.urlopen(request).read()
    
    fhandle = open("./baidu.html", "wb")
    fhandle.write(reponse)
    fhandle.close()

    代理服务器的设置

    应用场景:使用同一个IP去爬取同一个网站上的网页,久了之后会被该网站服务器屏蔽。 
    解决方法:使用代理服务器。 (使用代理服务器去爬取某个网站的内容的时候,在对方的网站上,显示的不是我们真实的IP地址,而是代理服务器的IP地址)

    def use_proxy(proxy_addr,url):
        import urllib.request
        proxy=urllib.request.ProxyHandler({'http':proxy_addr})
        opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
        urllib.request.install_opener(opener)
        data=urllib.request.urlopen(url).read().decode('utf8')
        return data
    
    proxy_addr='61.163.39.70:9999'
    data=use_proxy(proxy_addr,'http://www.baidu.com')
    print(len(data))

    Cookie的使用

    应用场景:爬取的网页涉及登录信息。访问每一个互联网页面,都是通过HTTP协议进行的,而HTTP协议是一个无状态协议,所谓的无状态协议即无法维持会话之间的状态。

    import urllib.request
    import urllib.parse
    import urllib.error
    import http.cookiejar
    
    url='http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=La2A2'
    data={
        'username':'zhanghao',
        'password':'mima',
    }
    postdata=urllib.parse.urlencode(data).encode('utf8')
    header={
        'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
    }
    
    request=urllib.request.Request(url,postdata,headers=header)
    #使用http.cookiejar.CookieJar()创建CookieJar对象
    cjar=http.cookiejar.CookieJar()
    #使用HTTPCookieProcessor创建cookie处理器,并以其为参数构建opener对象
    cookie=urllib.request.HTTPCookieProcessor(cjar)
    opener=urllib.request.build_opener(cookie)
    #将opener安装为全局
    urllib.request.install_opener(opener)
    
    try:
        reponse=urllib.request.urlopen(request)
    except urllib.error.HTTPError as e:
        print(e.code)
        print(e.reason)
    
    fhandle=open('./test1.html','wb')
    fhandle.write(reponse.read())
    fhandle.close()
    
    url2='http://bbs.chinaunix.net/forum-327-1.html'   #打开test2.html文件,会发现此时会保持我们的登录信息,为已登录状态。也就是说,对应的登录状态已经通过Cookie保存。
    reponse2=urllib.request.urlopen(url)
    fhandle2=open('./test2.html','wb')
    fhandle2.write(reponse2.read())
    fhandle2.close()
  • 相关阅读:
    Linux日志管理系统rsyslog
    Linux访问权限控制及时间同步实践
    Linux系统自动化安装之cobbler实现
    【转】java取整和java四舍五入方法
    The web application [ ] registered the JDBC driver [net.sourceforge.jtds.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver
    Python学习笔记之函数式编程
    Java去重字符串的两种方法以及java中冒号的使用
    Python学习之字符串格式化
    Python学习之文件操作
    Python学习笔记之爬虫
  • 原文地址:https://www.cnblogs.com/it-tsz/p/9787151.html
Copyright © 2011-2022 走看看