美文网首页
爬虫基础

爬虫基础

作者: 帅猪佩奇 | 来源:发表于2018-12-12 21:05 被阅读12次

    python爬虫基础

    python requests常用库 

    [文章链接](https://www.cnblogs.com/lilinwei340/p/6417689.html)

    python2.x与3.x

    urllib库在python2与python3中的区别

    Urllib是python提供的一个用于操作url的模块。

    在python2中,有urllib库和urllib2库。在python3中,urllib2合并到urllib库中,我们爬取网页的时候,经常用到这个库。

    升级合并后,模块中包的位置变化的地方较多。

    以下是python2与python3中常用的关于urllib库的变化:

    1.在python2中使用import urllib2————对应的,在python3中会使用import urllib.request,urllib.error

    2.在python2中使用import urllib————对应的,在python3中会使用import urllib.request,urllib.error,urllib.parse

    3.在python2中使用import urlparse————对应的,在python3中会使用import urllib.parse

    4.在python2中使用urllib2.urlopen————对应的,在python3中会使用urllib.request.urlopen

    5.在python2中使用urllib.urlencode————对应的,在python3中会使用urllib.parse.urlencode

    6.在python2中使用urllib.quote————对应的,在python3中会使用urllib.request.quote

    7.在python2中使用cookielib.CookieJar————对应的,在python3中会使用http.CookieJar

    8.在python2中使用urllib2.Request————对应的,在python3中会使用urllib.request.Request

    9.cookielib 用 http.cookiejar 代替

    10.print " "  用 print(" ") 代替

    11.urllib2.URLError 用 urllib.error.URLError 代替

    12.urllib2.HTTPError 用 urllib.error.HTTPError 代替

    13.except urllib2.URLError, e:  用  except urllib.error.URLError as e: 代替

    14.response.text返回的是Unicode类型的数据,

    response.content返回的是buyes型也就是二进制的数据

    参考:[文章](https://www.cnblogs.com/dplearning/p/4854746.html)

     简单测试爬行 

        from urllib.request import urlopen

        response = urlopen("http://www.baidu.com")

        a=response.read()

        print(a)//3.x版本print已经是一个函数,所以需要加括号

    上述代码就可轻松爬行出baidu的网页源码

    首先我们调用的是urllib2库里面的urlopen方法,传入一个URL,urlopen函数是有三个参数的,urlopen(url,data,timeout)

    url为需要打开的网址

    data为要传输的数据如post或者get参数

    timeout延迟设置

    headers设置模拟浏览器

    1. 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性,agent就是请求的身份,如果没有写入请求身份,那么服务器不一定会响应,所以可以在headers中设置agent。

    防盗链的时候服务器会识别headers中的refer是不是它自己,如果不是,服务器不会响应,所以我们需要在headers加入refer。例:

            headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5;  

             Windows NT)','Referer':'http://www.zhihu.com/articles' }  

    代理设置

    2. 假如一个网站它会检测某一段时间某个IP 的访问次数,如果访问次数过多,它会禁止你的访问。所以你可以设置一些代理服务器来帮助你做工作,每隔一段时间换一个代理。代码如:

            import urllib2  

    enable_proxy = True

            proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-  proxy.com:8080'})  

            null_proxy_handler = urllib2.ProxyHandler({})

            if enable_proxy:  

            opener = urllib2.build_opener(proxy_handler)  

            else:  

            opener = urllib2.build_opener(null_proxy_handler)  

            urllib2.install_opener(opener)  

    timeout延迟

    3. 有些网站等待超时,为了解决一些网站实在响应过慢而造成的影响,用到timeout参数

            import urllib2

            response = urllib2.urlopen('http://www.baidu.com', timeout=10)

    # python字符串str和字节数组相互转化方法 #

        # bytes object 

        b = b"example"

        # str object 

        s = "example"

        # str to bytes 

        bytes(s, encoding = "utf8") 

        # bytes to str 

        str(b, encoding = "utf-8") 

        # an alternative method 

        # str to bytes 

        str.encode(s) 

        # bytes to str 

        bytes.decode(b)

    爬行糗事百科

    贴脚本:

        #coding:utf-8

        import requests

        import base64

        import re

        url='https://www.qiushibaike.com/'

        s=requests.Session()

        r=s.get(url)

        b=r.text

        b=re.findall(r'(<div class="content">([\s\S])<span>([\s\S]){3}.*([\s\S]){2}</span>)+([\s\S])',b)

        #b =''.join(b)

        #a=matchaaa.replace(" "," ")

        f=open('1.txt')

        #b=matchaaa

        b=f.read()

        b=b.replace("<span>"," ")

        b=b.replace('<div class="content">'," ")

        b=b.replace("</span>"," ")

        b=b.replace("'\\n'"," ")

        b=b.replace("\\n"," ")

        if b:

            print(b)

    备注解析

    1.正则的search()函数,这个函数可以找到一个匹配的字符串返回,但是想找到所有匹配的字符串返回,需要使用findall,findall函数返回的总是正则表达式在字符串中所有匹配结果的列表,此处主要讨论列表中“结果”的展现方式,即findall中返回列表中每个元素包含的信息。因为返回形式为数组所以后面replace格式出了某些问题暂不明。

    2.b=r.text 或者 b=r.content.decode()都可 格式class str

    3.这里直接将抓取的b去replace报错,不明白为啥欢迎大牛指出,所以保存了一个文件中再读取,格式就正确。

    4.\n 正则那里需要转义一个\

    5.爬虫最好用beautiful soup,本文只是为了练习正则等python用法。

    参考:[文章](https://cuiqingcai.com/954.html)

    ---

    相关文章

      网友评论

          本文标题:爬虫基础

          本文链接:https://www.haomeiwen.com/subject/sofacqtx.html