[Python] 踩坑记录
主要记录一些常见到error但不记得怎么解决的问题。
1. 中文编码
python可用的中文编码有这些’big5’、‘big5hkscs’、‘cp950’、‘gb2312’、‘gbk’、‘gb18030’、‘hz’、‘iso2022_jp_2’,加粗几个是常用的,但是其他也是可以用的,中文编码出现问题的时候(尤其是存数据和读取数据时)换一个说不定就好了。
- 举个?
df.to_csv('./df.csv', encoding='gbk')
出现error:
‘gbk’ codec can’t encode character ‘\xa0’ in position 1: illegal multibyte sequence
# encoding改成gb18030就阔以了
df.to_csv('./df.csv', encoding='gb18030')
2. 重设dataframe的index
# 设成连续的数字
df.index = range(len(df))
# 以某一列为index
df.set_index('col_name', inplace = True)
3. 爬html前先看看有没有json
在爬html网页的时候,先不急着开始爬,到网络
里筛选出XHR
,说不定你要的东西就在某个json格式的文件里,岂不美哉,有时甚至可以绕开登录的坎。
4. 多条件筛选dataframe
条件与条件之间用&
链接,每个条件要用括号括起来!
- 举个?
df[df['id'] >= 5 & df['id'] <= 10]
然后就出错了:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
改成这样就没毛病了:
df[(df['id'] >= 5) & (df['id'] <= 10)]
5. webdriver版本和路径问题
- erro内容:
'chromedriver' executable needs to be in PATH
-
解决方案:
下载正确版本的driver并安装或放到对应路径。 -
传送门:
驱动下载:http://chromedriver.storage.googleapis.com/index.html
版本选择:https://blog.csdn.net/yoyocat915/article/details/80580066
教程:https://blog.csdn.net/tymatlab/article/details/78649727
存放位置备忘:/usr/local/bin/
6. matplotlib的中文显示问题
- 查看plt的字体:
from matplotlib import font_manager
a = sorted([f.name for f in font_manager.fontManager.ttflist])
for i in a:
print(i)
- 暂时设置:
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = 'Songti SC' # 通过上一步确认Songti SC是否存在,不存在则自己拷贝ttf进去
-
字体路径:
....../anaconda3/lib/pythonxx/site-packages/matplotlib/mpl-data/fonts/ttf
-
永久设置:
- 修改配置:
....../anaconda3/lib/pythonxx/site-packages/matplotlib/mpl-data/matplotlibrc
- 修改配置:
7. Jupyter-Notebook单元格输出覆盖
from easydl import clear_output
# 在需要清空输出时
clear_output()
8. chromedriver的问题
- steps:
- 确认chrome版本
- 下载对应驱动,驱动地址
- 如果本地曾有驱动
- 找到驱动的地址:
sudo find / -name chromedriver
(备用/usr/local/bin/chromedriver) - 拷贝进去
- 找到驱动的地址:
- 如果本地不曾有驱动
- 找到
9. 升级anaconda的python
conda update conda
conda update anaconda
# 不指定版本 - 更新到最新版本
conda update python
# 指定版本
conda install python=3.8