zoukankan      html  css  js  c++  java
  • 爬虫中常见问题

    1、爬取内容显示乱码

    1、原因:比如网页编码是gbk编码的,但是我们用了错误的方式比如utf-8解码,因而出现乱码
    2、基础知识:
        (1)python3.6 默认编码为Unicode;正常的字符串就是Unicode
        (2)计算机中存储的信息都是二进制的
        (3)编码decode:真实字符→二进制
        (4)解码encode:二进制→真实字符
        (5)一般来说在Unicode2个字节的,在UTF8需要3个字节;但对于大多数语言来说,只需要1个字节就能编码,如果采用Unicode会极大浪费,于是出现了变长的编码格式UTF8
        (6)GB2312的出现,基本满足了汉字的计算机处理需要,但对于人名、古汉语等方面出现的罕用字,GB2312不能处理,这导致了后来GBK及GB18030汉字字符集的出现。    
    3、各种编码方式:
        (1)ASCII :1字节8个bit位表示一个字符的编码格式,最多可以给256个字(包括字母、数字、标点符号、控制字符及其他符号)分配(或指定)数值。
        (2)ISO8859-1 :1字节8个bit位表示一个字符的编码格式,仅支持英文字符、数字及常见的符号,3.6%的全球网站使用这个编码。
        (3)GB2312:2字节16个bit位表示一个字符的编码格式,基本满足了汉字的计算机处理需要
        (4)GBK:2字节16个bit位表示一个字符的编码格式,GBK即汉字内码扩展规范
        (5)Unicode :2字节16个bit位表示一个字符的编码格式,基本能把全球所有字符表示完,
        (6)UTF8:变长字节编码格式,英文1字节,汉字3字节,较复杂的更高字节编码,
    4、实例:
    s = "" #默认Unicode编码
    print(s.encode("gbk")) #Unicode转gbk
    #输出2字节: b'xbaxc3'
    print(s.encode("utf-8")) #Unicode转utf-8
    #输出3字节:b'xe5xa5xbd'
    print(s.encode("gb2312")) #Unicode转gb2312
    #输出2字节:b'xbaxc3'
    print(s.encode("gb2312").decode("gb2312")) #Unicode解码为gb2312再编码为Unicode
    print(s.encode("utf8").decode("utf8")) #Unicode解码为utf8再编码为Unicode
    #输出:好

    (2)解决方法

    方法:
        查看网页是什么编码,并设置该编码格式,或者包含大于这个的编码,如gb2312编码的网页可以设置gbk的编码方式。
    代码:
        solution1:response.encoding = response.apparent_encoding
        solution2 :response.encoding = 'utf-8'
                    response.encoding = 'gbk'

    2、pymongo.errors.CursorNotFound:

    (1)原因:

    默认 mongo server维护连接的时间窗口是十分钟;默认单次从server获取数据是101条或者 大于1M小于16M的数据;所以默认情况下,如果10分钟内未能处理完数据,则抛出该异常。

    (2)解决方法:

    方法:
        no_cursor_timeout=True:设置连接永远不超时
        batch_size:估计每批次获取数据量的条数;让MongoDB客户端每次抓取的文档在10分钟内能用完
    代码:
        import pymongo
        client = pymongo.MongoClient(host='localhost', port=27017)
        db = client.test
        collection = db.testtable
        cursor = collection.find(no_cursor_timeout=True, batch_size=5)

    3、TypeError: can’t pickle _thread.lock objects和EOFError: Ran out of input

    (1)原因:

    1、进程池内部处理使用了pickle模块(用于python特有的类型和python的数据类型间进行转换)中的dump(obj, file, protocol=None,)方法对参数进行了封装处理.
    2、在参数传递中如果自定义了数据库存储类mongo或者redis等数据库,会造成进程池内部处理封装过程无法对其进行处理. 
    3、错误代码产生异常的实例1:
        import multiprocessing
        import pymongo
        class Test:
            def __init__(self, collection):
                self.collection = collection
            def savedata(self):
                self.collection.insert_one({'key': 'value'})
        def main():
            client = pymongo.MongoClient(host='localhost', port=27017)
            db = client.test
            collecttable = db.testtable
            test = Test(collecttable)
            p1 = multiprocessing.Process(target=test.savedata)
            p1.start()
            p1.join()
            print('进程已结束')
        if __name__ == '__main__':
            main()
    4、错误代码产生异常的实例2:
        import multiprocessing
        import pymongo
        class Test:
            def __init__(self):
                pass
            def savedata(self, collecttable):
                collecttable.insert_one({'key': 'value'})
        def main():
            client = pymongo.MongoClient(host='localhost', port=27017)
            db = client.test
            collecttable = db.testtable
            test = Test()
            p1 = multiprocessing.Process(target=test.savedata, args=(collecttable,))
            p1.start()
            p1.join()
            print('进程已结束')
        if __name__ == '__main__':
            main()

    (2)解决方法:

    方法:
        在参数传递时,不能将数据库集合作为类的参数进行传递,只能在函数里面创建使用数据库
    代码:
        import multiprocessing
        import pymongo
        class Test:
            def __init__(self):
                pass
            def savedata(self):
                client = pymongo.MongoClient(host='localhost', port=27017)
                db = client.test
                collecttable = db.testtable
                collecttable.insert_one({'key': 'value'})
        def main():
            test = Test()
            p1 = multiprocessing.Process(target=test.savedata)
            p1.start()
            p1.join()
            print('进程已结束')
        if __name__ == '__main__':
            main()

    4、redis.exceptions.DataError: Invalid input of type: ‘dict’. Convert to a byte, string or number first.

    (1)原因:

    1、redis存入数据类型错误,应该是字节或者是字符串或者是数字类型
    2、错误实例:
        from redis import StrictRedis
        dict = {'key': 'value'}
        r = StrictRedis(host='localhost', port=6379)
        r.rpush('test', dict)

    (2)解决方法:

    方法:
        使用json模块,json.dumps(dict)可以将字典类型的转换为字符串
    代码:
        import json
        from redis import StrictRedis
        dict = {'key': 'value'}
        r = StrictRedis(host='localhost', port=6379)
        data = json.dumps(dict)
        r.rpush('test', data)
        print(r.lpop('test'))
        #输出: b'{"key": "value"}'

    5、json.dumps()中文未正确显示

    (1)原因:

    1、json.dumps序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False:
    2、实例代码:
        import json
        dict = {'key': '测试'}
        print(json.dumps(dict))
        # 输出:{"key": "u6d4bu8bd5"}

    (2)解决方法:

    方法:
        json.dumps(dict,ensure_ascii = False)
    代码:
        import json
        dict = {'key': '测试'}
        print(json.dumps(dict, ensure_ascii=False))
        #输出: {"key": "测试"}

    6、AttributeError: ‘NoneType’ object has no attribute ‘decode’

    (1)原因:

    1、redis数据库为空,未取到数据,返回类型是NoneType类型
    2、错误实例:
        from redis import StrictRedis
        r = StrictRedis(host='localhost', port=6379)
        print(r.lpop('test').decode('utf-8'))

    (2)解决方法:

    1、确保redis里面有数据,先存数据,再取数据
    2、代码:
        import json
        from redis import StrictRedis
        r = StrictRedis(host='localhost', port=6379)
        dict = {'key': '测试'}
        data = json.dumps(dict, ensure_ascii=False)
        r.rpush('test', data)
        print(r.lpop('test').decode('utf-8')) #redis取出来的数据为字节类型,需要编码decode
        #输出:{"key": "测试"}

    7、如果代理设置成功,最后显示的IP应该是代理的IP地址,但是最终还是我真实的IP地址,为什么?

    获取代理并检测有效性:https://github.com/Shirmay1/Python/blob/master/Proxyip/xici.py
    (1)原因:

    requests.get(url,headers=headers,proxies=proxies)
    1、proxies在你访问http协议的网站时用http代理,访问https协议的网站用https的代理
    2、所以你的proxy需要根据网站是http还是https的协议进行代理设置,这样才能生效

    (2)解决方法:

    1、方法:
        如果proxies ={'http': 'http://112.85.169.206:9999'},
        http的测试网站'http://icanhazip.com'
        如果proxies ={'https': 'https://112.85.129.89:9999'}
        https的测试网站https://www.baidu.com/
    2、代码:
        proxies ={'http': 'http://112.85.169.206:9999'}
        r = requests.get('http://icanhazip.com', headers=headers, proxies=proxies, timeout=2)
        proxies ={'https': 'https://112.85.129.89:9999'}
        r = requests.get('https://www.baidu.com/', headers=headers, proxies=proxies, timeout=2)
    ···

    8、HTTPConnectionPool

    (1) Max retries exceeded with url

    1、报错:
        a.HTTPConnectionPool(host='XXX', port=XXX): Max retries exceeded with url: XXXX(Caused by ProxyError('Cannot connect to proxy.', ConnectionResetError(10054, '远程主机强迫关闭了一个现有的连接。', None, 10054, None)))
        b.HTTPConnectionPool(host='XXX', port=XXX): Max retries exceeded with url: XXXX(Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020B87AAC4E0>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。')))
        c.HTTPConnectionPool(host='XXX', port=XXX): Max retries exceeded with url: XXXX (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response')))
    2、原因:
        a.http连接太多没有关闭导致
        b.访问次数频繁,被禁止访问
        c.每次数据传输前客户端要和服务器建立TCP连接,为节省传输消耗,默认为keep-alive,即连接一次,传输多次,然而在多次访问后不能结束并回到连接池中,导致不能产生新的连接
    3、解决方法:
        a.增加连接次数
        b.requests使用了urllib3库,默认的http connection是keep-alive的,requests设置False关闭。
        c.headers中的Connection默认为keep-alive,将headers中的Connection一项置为close
    4、小知识补充:
        a.会话对象requests.Session能够跨请求地保持某些参数,比如cookies,即在同一个Session实例发出的所有请求都保持同一个cookies,而requests模块每次会自动处理cookies,这样就很方便地处理登录时的cookies问题。

    (2)代码

    """增加重连次数,关闭多余连接,使用代理"""
    import requests
    headers = {'Connection': 'close'}
    requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数
    s = requests.session()
    s.keep_alive = False # 关闭多余连接
    s.proxies = {"https": "47.100.104.247:8080", "http": "36.248.10.47:8080", } # 使用代理
    try:
        s.get(url) # 访问网址
    except Exception as err:
        pass
    """This will GET the URL and retry 3 times in case of requests.exceptions.ConnectionError. backoff_factor will help to apply delays between attempts to avoid to fail again in case of periodic request quo"""
    import requests
    from requests.adapters import HTTPAdapter
    from requests.packages.urllib3.util.retry import Retry
    session = requests.Session()
    retry = Retry(connect=3, backoff_factor=0.5)
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    try:
        s.get(url) # 访问网址
    except Exception as err:
        pass

    欢迎关注公众号:Python爬虫数据分析挖掘,回复【开源源码】免费获取更多开源项目源码

    公众号每日更新python知识和【免费】工具

    耐得住寂寞,才能登得顶
    Gitee码云:https://gitee.com/lyc96/projects
  • 相关阅读:
    linux高编进程------system函数使用
    linux高编进程------用户权限
    linux高编进程------支持外部命令的shell实现(glob、strsep、fork)
    linux高编进程------exec函数族
    linux高编进程------进程分配
    1299. 将每个元素替换为右侧最大元素
    719. 找出第 k 小的距离对(二分)
    35. 搜索插入位置(二分)
    文件打不开,移到废纸篓
    119. 杨辉三角 II
  • 原文地址:https://www.cnblogs.com/chenlove/p/13663440.html
Copyright © 2011-2022 走看看