python笔记2

文章链接:http://www.liuschen.com

1.安装工具包

需要安装pandas_datareader和pandas

pip install pandas
pip install pandas_datareader

但是会出现错误:

ImportError: cannot import name PandasError

解决办法是更换pandas的版本,执行

pip install -U pandas==0.19.2

替换掉了我已经安装的0.20.1版本

2.股票代码含义

沪市A股票买卖的代码是以600、601或603打头

3.爬虫

BeautifulSoup文档

安装BeautifulSoup用来解析xml/Html文件:

pip install beautifulsoup4

引入项目:from bs4 import BeautifulSoup,使用:

soup = BeautifulSoup(getHtml(dstUrl), 'html.parser', from_encoding='utf-8')
print soup.find_all('title')

soup.find_all("title")
# [<title>The Dormouse's story</title>]

soup.find_all("p", "title")
# [<p class="title"><b>The Dormouse's story</b></p>]

soup.find_all("a")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.find_all(id="link2")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

import re
soup.find(text=re.compile("sisters"))

data_soup.find_all(attrs={"data-foo": "value"})

通过find_all得到的列表中的HTML段都可以再次应用find,find_all过滤

4.数据库通信乱码

将爬到的数据写入数据库中,发现有几处编码格式会产生影响:

  1. py文件编码

window系统,所以是ascii

  1. 系统编码

    import sys
    reload(sys)
    sys.setdefaultencoding(‘gbk’)

  2. 连接数据库的编码

    db = MySQLdb.connect(“ip”,”user”,”pwd”,”house_msg”,charset=”gbk”)

  3. 写入字符的编码

    soup = BeautifulSoup(getHtml(dstUrl), ‘html.parser’, from_encoding=’utf-8’)

  4. 数据库本身的字符集编码

一开始我将所有都改为utf-8格式(为了适应数据库),但是发现py文件本身是ascii编码格式,根本不能写入数据库,即使将当前文件编码改为utf-8,它的引用文件依然会报这个错误,于是将系统编码改为gbk,可写入,但毫无疑问,数据库中表出现了乱码。最好智能将系统编码和连接数据库的编码以及数据库本身的字符集编码都改为了gbk,乱码问题才解决。

异常:

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

Python操作数据库写入时,字符串数据中如果有u’\xa0’将不能正确转码,需要string.replace(u’\xa0’,u’‘)替换掉

Loading Disqus comments...
Table of Contents