Python3.5 ‘wb’与‘w’区别以及写入excel的常见错误

望共同进步

转载请注明地址:http://blog.csdn.net/weixin_39701039/article/details/79576549

"r"   以读方式打开,只能读文件 , 如果文件不存在,会发生异常

"w" 以写方式打开,只能写文件, 如果文件不存在,创建该文件;如果文件已存在,先清空,再打开文件                                                
"rb"   以二进制读方式打开,只能读文件 , 如果文件不存在,会发生异常

"wb" 以二进制写方式打开,只能写文件, 如果文件不存在,创建该文件;如果文件已存在,先清空,再打开文件

这里结合前面写的 Python3.5 爬虫之由浅入深(三、html转excel)来看看'w'和'wb'的区别,已经延伸的说说爬取文件成伪excel时遇到的问题;

一:UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 13785: illegal multibyte sequence 

#coding:utf-8
#python3.5.1

import re
import requests
import time
import os
from bs4 import BeautifulSouppath = r'G:\任务20180312'
url = 'http://tjj.suqian.gov.cn/stjj/ndsj/201609/d9bbdb1109cf497e80e59c56ce216ce0.shtml'
url_prefix = 'http://tjj.suqian.gov.cn/'

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }def get_Soup(url):response = requests.get(url,headers = headers,timeout = 120)response.encoding = 'utf-8'
    res = response.textsoup = BeautifulSoup(res,'html.parser')return soup
soup = get_Soup(url)
#print(soup)
table = soup('table',style="WIDTH: 542pt; BORDER-COLLAPSE: collapse")[0] #table类型为<class 'bs4.element.Tag'>
print(type(table))      #转变为字符串
result1 = str(table)
#print(result1)

tbody = soup('tbody')[0]   #tbody类型为<class 'bs4.element.Tag'>
result2 = str(tbody)     #转变为字符串

with open(r'G:\任务20180312\test\html_excel/test1.xls','w') as f1:f1.write(result1)

#结果:

因为如果在window下运行,对于Unicode字符,需要print出来的话,由于本地系统是Windows中的cmd,默认codepage是CP936,即GBK的编码,所以python解释器需要先将上述的Unicode字符编码为GBK,然后再在cmd中显示出来。但是由于该Unicode字符串中包含一些GBK中无法显示的字符,导致此时提示“’gbk’ codec can’t encode”的错误的。

这个时候我们可以在with open(..,)括号里加入编码方式,'utf-8',如下代码:

#coding:utf-8
#python3.5.1

import re
import requests
import time
import os
from bs4 import BeautifulSouppath = r'G:\任务20180312'
url = 'http://tjj.suqian.gov.cn/stjj/ndsj/201609/d9bbdb1109cf497e80e59c56ce216ce0.shtml'
url_prefix = 'http://tjj.suqian.gov.cn/'

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }def get_Soup(url):response = requests.get(url,headers = headers,timeout = 120)response.encoding = 'utf-8'
    res = response.textsoup = BeautifulSoup(res,'html.parser')return soup
soup = get_Soup(url)
#print(soup)
table = soup('table',style="WIDTH: 542pt; BORDER-COLLAPSE: collapse")[0] #table类型为<class 'bs4.element.Tag'>
print(type(table))      #转变为字符串
result1 = str(table)
#print(result1)

tbody = soup('tbody')[0]   #tbody类型为<class 'bs4.element.Tag'>
result2 = str(tbody)     #转变为字符串


with open(r'G:\任务20180312\test\html_excel/test1.xls','w',encoding='utf-8') as f1:f1.write(result1)

#结果:

二:ValueError: binary mode doesn't take an encoding argument

如下代码:

#coding:utf-8
#python3.5.1

import re
import requests
import time
import os
from bs4 import BeautifulSouppath = r'G:\任务20180312'
url = 'http://tjj.suqian.gov.cn/stjj/ndsj/201609/d9bbdb1109cf497e80e59c56ce216ce0.shtml'
url_prefix = 'http://tjj.suqian.gov.cn/'

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }def get_Soup(url):response = requests.get(url,headers = headers,timeout = 120)response.encoding = 'utf-8'
    res = response.textsoup = BeautifulSoup(res,'html.parser')return soup
soup = get_Soup(url)
#print(soup)
table = soup('table',style="WIDTH: 542pt; BORDER-COLLAPSE: collapse")[0] #table类型为<class 'bs4.element.Tag'>
print(type(table))      #转变为字符串
result1 = str(table)
#print(result1)

tbody = soup('tbody')[0]   #tbody类型为<class 'bs4.element.Tag'>
result2 = str(tbody)     #转变为字符串


with open(r'G:\任务20180312\test\html_excel/test1.xls','wb',encoding='utf-8') as f1: f1.write(result1)

#结果:

因为'wb'是以二进制写入文件,而result1是字符串(str),所以报错,写入文件为0kb,即没有结果

这里可以把result1转变问字节串 bytes(result1)

如下:

#coding:utf-8
#python3.5.1

import re
import requests
import time
import os
from bs4 import BeautifulSouppath = r'G:\任务20180312'
url = 'http://tjj.suqian.gov.cn/stjj/ndsj/201609/d9bbdb1109cf497e80e59c56ce216ce0.shtml'
url_prefix = 'http://tjj.suqian.gov.cn/'

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }def get_Soup(url):response = requests.get(url,headers = headers,timeout = 120)response.encoding = 'utf-8'
    res = response.textsoup = BeautifulSoup(res,'html.parser')return soup
soup = get_Soup(url)
#print(soup)
table = soup('table',style="WIDTH: 542pt; BORDER-COLLAPSE: collapse")[0] #table类型为<class 'bs4.element.Tag'>
print(type(table))      #转变为字符串
result1 = str(table)
#print(result1)

tbody = soup('tbody')[0]   #tbody类型为<class 'bs4.element.Tag'>
result2 = str(tbody)     #转变为字符串



with open(r'G:\任务20180312\test\html_excel/test1.xls','wb') as f1:f1.write(bytes(result1,encoding='utf-8'))

#结果:

注意,这里with open(..)括号里没有encoding=部分了,因为二进制不能在进行编码了,不然会报错ValueError: binary mode doesn't take an encoding argument

bytes(result1,encoding='utf-8')这里是因为转字符串为二进制需要编码方式

三:得到的文件不是我们想要的表格形式,而是一堆字符串

#coding:utf-8
#python3.5.1

import re
import requests
import time
import os
from bs4 import BeautifulSouppath = r'G:\任务20180312'
url = 'http://tjj.suqian.gov.cn/stjj/ndsj/201609/d9bbdb1109cf497e80e59c56ce216ce0.shtml'
url_prefix = 'http://tjj.suqian.gov.cn/'

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }def get_Soup(url):response = requests.get(url,headers = headers,timeout = 120)response.encoding = 'utf-8'
    res = response.textsoup = BeautifulSoup(res,'html.parser')return soup
soup = get_Soup(url)
#print(soup)
table = soup('table',style="WIDTH: 542pt; BORDER-COLLAPSE: collapse")[0] #table类型为<class 'bs4.element.Tag'>
print(type(table))      #转变为字符串
result1 = str(table)
#print(result1)

tbody = soup('tbody')[0]   #tbody类型为<class 'bs4.element.Tag'>
result2 = str(tbody)     #转变为字符串

with open(r'G:\任务20180312\test\html_excel/test1.xls','w',encoding='utf-8') as f1:f1.write(result1)with open(r'G:\任务20180312\test\html_excel/test2.xls', 'w',encoding='utf-8') as f2:f2.write(result2)

#结果:

那现在我们发现区别在于result1和result2

右键网页打开源代码,来查看区别:

区别在于result1比result2少了些代码(因为我们存入的文件形式为伪excel,所以这个是有关系的),现在有html工具(这里我用的editplus)分别将这两部分代码以浏览器形式打开:

PS:所以我们要把带样式的代码也抓取下来,建议可以看看html5和css,了解一下

望有所帮助,望采纳!!

Python3.5 ‘wb’与‘w’区别以及写入excel的常见错误相关推荐

  1. python列表逐行写入excel_python表格数据到excel-想问下python3怎么将列表数据逐行写入excel表格呢?...

    如何用python将数据写入excel表格 简介绍一下这两个库,先说xlrd,这个Excel比较,各种方法使用起来方便: bk = xlrd.open_workbook('your.xls') sh ...

  2. python打开文件的语法_python27语法Python文件打开方式实例详解【a、a+、r+、w+区别】...

    本文实例讲述了Python文件打开方式.分享给大家供大家参考,具体如下: 第一步 排除文件打开方式错误: r只读,r+读写,不创建 w新建只写,w+新建读写,二者都会将文件内容清零 (以w方式打开,不 ...

  3. python3读取excel数据-Python3读取和写入excel表格数据的示例代码

    python操作excel主要用到 xlrd 和 xlwt 这两个库,xlrd读取excel表格数据, 支持 xlsx和xls格式的excel表格 :xlwt写入excel表格数据: 一.python ...

  4. python输入和输出的区别_python2和python3的输入和输出区别介绍

    Python3 输入和输出 输出格式美化 Python两种输出值的方式: 表达式语句和 print() 函数. 第三种方式是使用文件对象的 write() 方法,标准输出文件可以用 sys.stdou ...

  5. python3 reqeusts后写入excel

    用python通过手机号批量辨别运营商并写入excel 初始文件: 具体代码: #coding=utf-8 import requests import re import xlrd import x ...

  6. Python3读取和写入excel表格数据

    目录 一.python读取excel表格数据 1.读取excel表格数据常用操作 2.xlrd模块的主要操作 3.读取单元格内容为日期时间的方式 4. 读取合并单元格的数据 二.python写入exc ...

  7. python3 写入excel表格数据_Python3读取和写入excel表格数据

    目录 python操作excel主要用到 xlrd和xlwt 这两个库,xlrd读取excel表格数据, 支持 xlsx和xls格式的excel表格 :xlwt写入excel表格数据: 一.pytho ...

  8. python字符串写入excel-使用python将数据写入excel

    由于经常需要用到这方面的内容,所以要好好记录一下,省的以后老找了 使用的代码版本为 Python3 首先呢,数据是这个样子的 V04002 V01000 V04001 V10004 V12001 V1 ...

  9. python把数据写入excel_Python读取和写入Excel文件(转)

    学习用Python处理Excel文件,这里主要用xlrd和xlwt模块,用前需要安装!本文是来自几篇博客和官网tutorial的整理,主要是一个入门.更多的处理Excel的方法请到官网学习,链接为:h ...

最新文章

  1. 模拟内存计算如何解决边缘人工智能推理的功耗挑战
  2. 在matlab中可以计算式子的最大值吗,matlab求最大值
  3. grabcut.cpp:380: error: (-215) !bgdSamples.empty() !fgdSamples.empty() in function initGMMs
  4. mysql如何算值_如何计算MySQL中具有特定值的列数?
  5. 5界面怎么做窗帘拉动的效果_别让土味窗帘毁了你的家
  6. [译文]Domain Driven Design Reference(三)—— 模型驱动设计的构建模块
  7. python利用pandas和xlrd读取excel,特征筛选列
  8. 【NLP】用code2vec、glow和spaCy进行词嵌入
  9. Gridview应用技巧——如何为行添加事件
  10. mysql semi sync_MySQL Semisync
  11. HttpsessionListener 实现在线人数统计
  12. break continue
  13. 关于字符 字节 python3
  14. SM3算法的C++实现(代码)
  15. 量化交易学习——熟读github上的开源交易策略框架
  16. python爬虫获取维基百科词条
  17. IPQ5000/IPQ5010/IPQ5018/方案WiFi6开发 工业5G CPE
  18. QT手动添加Q_OBJECT报错解决方法记录
  19. python写一个类方法_重写python脚本,在脚本的每个类中注入一个方法 - python
  20. 将POLY-YOLO代码跑起来的环境配置,poly-yolo训练自己的数据集

热门文章

  1. 汽车电子之NXP车规级芯片
  2. [翻译]C#和COM的互操作
  3. Windows10神州网信版的安装
  4. python 空数组判断
  5. 机器学习-无监督学习-聚类:聚类方法(一)--- k-Means(k-均值)算法,k-Means++算法【使用最大期望值算法(EM算法)来求解】
  6. 前端JavaScript实现垃圾分类小游戏教程
  7. 2023年跨年代码(新年祝福语生成器)
  8. 一阶常微分方程(一)| 存在与唯一性定理 + 变量分离 + 齐次方程
  9. 设计商品分类表 mysql_商品分类表设计
  10. http请求HttpServletRequest详解