美文网首页
Urllib库添加headers的一般方法

Urllib库添加headers的一般方法

作者: 木火_magic | 来源:发表于2022-04-07 22:04 被阅读0次

    在使用urllib请求一些网站的时候,会发生一些错误,被拒绝访问,我们需要加上请求头才可以完成网页的抓取,不然无法从服务器端得到正确的返回内容,下面介绍两个添加请求头的方法。

    python默认编码问题,运行如下代码会报错

    import urllib.request
    try:
        url="https://www.jianshu.com/"
    
        req=urllib.request.Request(url=url)
    
        req.add_header("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36")
        file=urllib.request.urlopen(req,timeout=10.1)
    
        print(file.read().decode("utf-8",'ignore'))
    except Exception as e:
        print("时间超时",str(e))
    

    报错如下:

    image.png

    显示【时间超时 'gbk' codec can't encode character '\xa9' in position 19672: illegal multibyte sequence】
    看完贴子后,才知道,原来是python的print()方法的问题。
    在python中, print()方法在Win7的默认编码是gbk,它在打印时,并不是所有的字符都支持的。
    而且这个问题一般也就是在cmd中才会有。 在cmd中是改变标准输出编码:

    使用一下两句代码可以解决在CMD中运行出错的问题

    1 import os,sys,io 
    2 sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') 
    

    方法一:借助build_opener和addheaders完成

    import urllib.request
    import os,sys,io 
    #解决编码问题,修改默认编码为gb18030
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')
    url="https://www.jianshu.com/"
    #注意:在urllib 中headers是元组
    headers=("User-Agent","UMozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36")
    opener=urllib.request.build_opener()
    opener.addheaders=[headers]
    data=opener.open(url)
    print(data.read().decode())
    

    注意:此处的headers要写为一个元组类型才可以。写为字典类型的话会报错!

    # 案例1
    import urllib.request
    import os,sys,io 
    #解决编码问题,修改默认编码为gb18030
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') 
    url="https://www.jianshu.com/"
    #注意:在urllib 中这种的headers 是需要是字典的
    headers={'User-Agent':"UMozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36"}
    req=urllib.request.Request(url=url,headers=headers)
    file=urllib.request.urlopen(req)
    #出现有些解码错误的话,加上“ignore”就可以啦
    print(file.read().decode("utf-8",'ignore'))
    

    注意:此处的headers要写为一个字典类型才可以。
    创建一个Reques对象,把需要的headers,url,proxy 都放进去,或者在post 请求中还可以把编码过后的data 值放进去,再用urlopen 打开,就比较方便了。

    此外:这种方法还可以用add_headers()来添加headers,代码如下:

    import urllib.request
    import os,sys,io 
    #解决编码问题,修改默认编码为gb18030
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')
    try:
        url="https://www.jianshu.com/"
        req=urllib.request.Request(url=url)
        req.add_header("User-Agent","UMozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36")
        file=urllib.request.urlopen(req,timeout=10.1)
        print(file.read().decode("utf-8",'ignore'))
    except Exception as e:
        print("时间超时",str(e))
    
    编码名称          用途
    utf8            所有语言
    gbk             简体中文
    gb2312          简体中文
    gb18030         简体中文
    big5            繁体中文
    big5hkscs       繁体中文
    

    相关文章

      网友评论

          本文标题:Urllib库添加headers的一般方法

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