Chinaunix首页 | 论坛 | 博客
  • 博客访问: 18994
  • 博文数量: 3
  • 博客积分: 258
  • 博客等级: 二等列兵
  • 技术积分: 40
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-06 17:17
文章分类

全部博文(3)

文章存档

2014年(2)

2011年(1)

最近访客

分类: Python/Ruby

2014-10-28 10:45:55


点击(此处)折叠或打开

  1. # encoding:utf-8
  2.     import sys
  3.     import re
  4.     import pymssql
  5.     from urllib2 import Request, urlopen, URLError, HTTPError
  6.       
  7.     def get_packet(url):
  8.         packet = urlopen(url)
  9.         content = packet.read()
  10.         return content
  11.     def get_data(packet):
  12.         global items
  13.         global items2
  14.         xiangmu = '~'
  15.         tmp = re.findall(r'(.*)',packet)
  16.         tmp2 = re.findall('(.*)',packet)
  17.         if tmp is not None:
  18.             items = tmp
  19.         if tmp2 is not None :
  20.             items2 = [x for x in tmp2 if '&' not in x]
  21.     def save_data():
  22.       
  23.         server = "A853F747DDE4458\SQLEXPRESS"
  24.         user = "sa"
  25.         password = "123456"
  26.       
  27.         conn = pymssql.connect(server, user, password, "stock")
  28.         cursor = conn.cursor()
  29.         sql = "INSERT INTO assets_and_liabilities VALUES (%d, %s, %s, %s)"
  30.         j=2;
  31.         for i in range(0,len(items)):
  32.             cursor.execute(sql,(ID, items2[0], items[i] ,items2[i+j]))
  33.             j=j+1
  34.     # you must call commit() to persist your data if you don't set autocommit to True
  35.         conn.commit()
  36.         conn.close()
  37.     if __name__=='__main__':
  38.         url = 'http://stock.finance.qq.com/corp1/cbsheet.php?zqdm=600787&type=2014'
  39.         packet = get_packet(url)
  40.         items = []
  41.         items2 = []
  42.         ID = 600787
  43.         if packet =='~

此次代码更新了以下内容:

1、对抓取到的数据进行处理,用语句

点击(此处)折叠或打开

  1. if tmp2 is not None :
  2.         items2 = [x for x in tmp2 if '&' not in x]
对“ ”这个数据作丢弃处理。新生成一个列表赋值给items2.

2、增加写入数据库的语句,把数据批量插入数据库表中,通过导入pymssql库,即可用python操作mssql数据库。

3、修正items和items2为全局变量,在函数中加global items即可,否则在get_data函数中给items和items2赋值后,运行到save_data函数时,items和items2仍然是初始 值。get_data的赋值会不起作用。(此问题困扰了好久,真失败。)

阅读(1544) | 评论(0) | 转发(0) |
0

上一篇:python爬虫笔记(1)

下一篇:没有了

给主人留下些什么吧!~~