美文网首页爬虫项目汇总
获取市场上的股票代码

获取市场上的股票代码

作者: 一秆子数码 | 来源:发表于2019-05-05 17:33 被阅读0次

使用python2.7,rullib2,re

http://www.txsec.com/inc1/gpdm.asp进行数据获取,见代码:

# -*- coding: utf-8 -*-
import urllib
import urllib2
import re
import csv
 
post_url = 'http://www.txsec.com/inc1/gpdm.asp'
header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',
             'Origin':'http://www.cninfo.com.cn'}
try:
    request = urllib2.Request(post_url,headers=header)
    response = urllib2.urlopen(request)
    pageCode = response.read().decode('gbk')
except Exception as e:
    print e
 
pattern = re.compile('<tr .*?>.*?<td .*?>(.*?)</td>.*?<td .*?>(.*?)</td>.*?'+
                     '<td .*?>(.*?)</td>.*?<td .*?>(.*?)</td>.*?</tr>.*?'+'<tr>.*?<td .*?>(.*?)</td>.*?<td .*?>(.*?)</td>.*?'+
                     '<td .*?>(.*?)</td>.*?<td .*?>(.*?)</td>.*?</tr>',re.S)
print("匹配模式是:",pattern)
'''
通过python的help函数查看compile含义:
help(re.compile)
compile(pattern, flags=0) 
Compile a regular expression pattern, returning a pattern object.
通过help可以看到compile方法的介绍,返回一个pattern对象,但是却没有对第二个参数flags进行介绍。第二个参数flags是匹配模式,可以使用按位或’|’表示同时生效,也可以在正则表达式字符串中指定。Pattern对象是不能直接实例化的,只能通过compile方法得到。匹配模式有: 
1).re.I(re.IGNORECASE): 忽略大小写 
2).re.M(MULTILINE): 多行模式,改变’^’和’$’的行为 
3).re.S(DOTALL): 点任意匹配模式,改变’.’的行为 
4).re.L(LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定 
5).re.U(UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性 
6).re.X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释
'''
items = re.findall(pattern,pageCode)
# print("查询到的数据是:",items)
#stockFile = file('stock.csv','w')
#write = csv.writer(stockFile)
stockFile = file('stock.txt','w')
stockDict = {}
for item in items:
    #content = [
       # (item[0]+':',item[1].encode('gbk')),
       # (item[2]+':',item[3].encode('gbk'))
      #  ]
    #content = re.sub(removeNoneLine,"\n",content)
    #write.writerows(content)
    stockDict[item[0].strip()]=item[1].strip()
    stockDict[item[2].strip()]=item[3].strip()
    stockDict[item[4].strip()]=item[5].strip()
    stockDict[item[6].strip()]=item[7].strip()
 
keys=stockDict.keys()
print(keys)
keys.sort()
for item in keys:
    content = item+':'+stockDict[item]+'\n'
    stockFile.write(content.encode('gbk'))
stockFile.close()

相关文章

网友评论

    本文标题:获取市场上的股票代码

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