爬虫中常见问题

作者: 生信师姐 | 来源:发表于2020-09-12 08:58 被阅读0次

    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'\xba\xc3'
    print(s.encode("utf-8")) #Unicode转utf-8
    #输出3字节:b'\xe5\xa5\xbd'
    print(s.encode("gb2312")) #Unicode转gb2312
    #输出2字节:b'\xba\xc3'
    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": "\u6d4b\u8bd5"}
    

    (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
    

    9、socket.timeout:

    (1)socket.timeout

    1、报错:
        a.socket.timeout: timed out
    2、原因:
        a.socketTimeout:指客户端和服务进行数据交互的时间,是指两者之间如果两个数据包之间的时间大于该时间则认为超时,而不是整个交互的整体时间,比如如果设置1秒超时,如果每隔0.8秒传输一次数据,传输10次,总共8秒,这样是不超时的。而如果任意两个数据包之间的时间超过了1秒,则超时。
        b.一次http请求,必定会有三个阶段,一:建立连接;二:数据传送;三,断开连接。当建立连接在规定的时间内(ConnectionTimeOut )没有完成,那么此次连接就结束了。后续的SocketTimeOutException就一定不会发生。只有当连接建立起来后,也就是没有发生ConnectionTimeOutException ,才会开始传输数据,如果数据在规定的时间内(SocketTimeOut)传输完毕,则断开连接。否则,触发SocketTimeOutException  
    3.解决方法:
        import socket
        socket.setdefaulttimeout(timeout)
    4.小知识补充:
        SocketTimeoutException一般是服务器响应超时,即服务器已经收到了请求但是没有给客户端进行有效的返回;
        ConnectTimeoutException指服务器请求超时,指在请求的时候无法客户端无法连接上服务端
    

    (2)代码

    import socket
    socket.setdefaulttimeout(timeout)
    try:
        pass
    except socket.timeout as err:
        pass
    
    

    10、try……except

    try:
        pass
    except requests.exceptions.ReadTimeout:
        pass
    except urllib3.exceptions.ReadTimeoutError:
        pass
    except TimeoutError:
        pass
    except urllib3.exceptions.NewConnectionError:
        pass
    except urllib3.exceptions.MaxRetryError:
        pass
    except requests.exceptions.ProxyError:
        pass
    

    11.lxml 解析

    (1)解析xml报错 ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

    大家都知道要使Python能识别中文,必须在python文件首部用“# coding=utf8”申明,告知python文件的编码方式。然而,如果在交互式开发环境中,也即是命令行模式下,如果使用“# coding=utf8”申明,就会得到系统报错

    例如:

    import requests
    from lxml import etree
    
    header = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'User-Agent': 'Mozilla/5.0 (compatible; ABrowse 0.4; Syllable)'
        }
    url = 'https://www.ncbi.nlm.nih.gov/geo/browse/?view=series&zsort=date&display=20&page=1'
    res = requests.get(url,headers = header).text
    print(res)
    
    tree = etree.HTML(res)
    tr_list = tree.xpath('//table[@id="geo_data"]/tbody/tr')
    
    for tr in tr_list:
        Accession = tr.xpath('./td[1]/a/text()')
        print(Accession)
    
    

    结果:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <head>
        <title>GEO Browser - GEO - NCBI</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="author" content="geo" />
        <meta name="keywords" content="NCBI, national institutes of health, nih, database, archive, central, bioinformatics,                 biomedicine, geo, gene, expression, omnibus, chips, microarrays, oligonucleotide, array, sage, CGH" />
        <meta name="description" content="Gene Expression Omnibus (GEO) is a database repository of high throughput                 gene expression data and hybridization arrays, chips, microarrays." />
        <meta name="ncbidialog" content="width: 330, modal: true" />
        <meta name="ncbi_app" content="geo" />
        <meta name="ncbi_pdid" content="browse" />
        <meta name="ncbi_phid" content="07516837D99B5A610000000000000001" />
        <meta name="ncbi_sessionid" content="07516837D99B5A61_0000SID" />
        <link rel="shortcut icon" href="/geo/img/OmixIconBare.ico" />
        <link rel="stylesheet" type="text/css" href="/geo/css/reset.css" />
        <link rel="stylesheet" type="text/css" href="/geo/css/geo.css" />
        <link rel="stylesheet" type="text/css" href="browse.css" />
        <script type="text/javascript" src="/core/jig/1.14.8/js/jig.min.js"></script>
        <script type="text/javascript" src="/geo/js/dd_menu.js"></script>
        <script type="text/javascript">
            jQuery.getScript("/core/alerts/alerts.js", function () {
                galert(['#crumbs_login_bar', 'body &gt; *:nth-child(1)'])
            });
        </script>
        <script type="text/javascript">
            var ncbi_startTime = new Date();
        </script>
      </head>
    ...
    ...
    ...
    </html>
    
    
    Traceback (most recent call last):
      File "C:/Users/Administrator/Desktop/temp/GEO.py", line 17, in <module>
        tree = etree.HTML(res)
      File "src\lxml\etree.pyx", line 3182, in lxml.etree.HTML
      File "src\lxml\parser.pxi", line 1871, in lxml.etree._parseMemoryDocument
    ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
    

    分析:lxml 不支持解析带有encoding 声明的字符串,例如 xml中以encoding="UTF-8"开头,需要转换成bytes类型。

    解决方案:

    res = requests.get(url,headers = header).content
    

    2.selenium处理alert弹出框

    import time
    from selenium import webdriver
    
    driver =webdriver.Chrome(r"D:\工具包\chromedriver.exe")
    driver.maximize_window()
    driver.implicitly_wait(6)
    driver.get("https://www.baidu.com")
    time.sleep(1)
    
    driver.execute_script("window.alert('这是一个测试Alert弹窗');")
    time.sleep(2)
    driver.switch_to_alert().accept()  # 点击弹出里面的确定按钮
    

    参考链接
    https://www.cnblogs.com/Summer-skr--blog/articles/11644161.html
    https://www.cnblogs.com/caodneg7/p/10279664.html
    https://www.cnblogs.com/wq-mr-almost/p/10209680.html
    https://www.cnblogs.com/CXMS/p/11424438.html
    https://www.cnblogs.com/qingdeng123/p/11329746.html
    https://www.cnblogs.com/luowenConnor/p/11482921.html
    https://www.cnblogs.com/heniu/p/9307242.html
    https://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_012_scrapy07.html

    相关文章

      网友评论

        本文标题:爬虫中常见问题

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