Pyhton3.x 爬虫 网页下载器 urllib 和 Pyhton2.x 网页下载器urllib2 的不同(pycharm编程细节)

Q1:AttributeError: 'module' object has no attribute 'request'

遇到builtins.AttributeError: 'module' object has no attribute 'xxx'的时候,直接import urllib.xxx就可以解决!(因为python3.X有时候不会将子模块自动导入进去,所以改成import urllib.request问题就解决了)

Q2: AttributeError: 'module' object has no attribute 'Request'

将urllib.Request(url)  改为urllib.request.Request(url)

Q3: NameError: name 'cookielib' is not defined

》》from http import cookiejar

cookiejar = http.cookiejar.CookieJar()

Q4: (考虑兼容python3和续行的方便性)捕获异常时尽量指明具体异常, 尽量不用 except Exception, 应该捕获 出了什么问题,而不是问题发生

EXAMPLE:

# please do as this (捕获具体异常)

try:

    import platform_specific_module

except ImportError:

    platform_specific_module = None

# You'd better not do like this (不要全局捕获)

try:

    import platform_specific_module

except:

platform_specific_module = None

 

猜你喜欢

转载自blog.csdn.net/weixin_37600848/article/details/83050821