加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

python抓取股票相关数据,实时行情,十大股东,全市场股票列表

(2017-12-26 15:47:31)
标签:

python

数据分析

入门

爬虫

股票

分类: Python




由于访问太频繁会被IP BAN,所以自己找代理,开线程去……

Python Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import requests
import re
from lxml import etree
import pandas as pd
import time


StockPriceUrl "http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/#code.phtml?year=#year&jidu=#jd"
StockListUrl "http://quote.eastmoney.com/stocklist.html"
StockInfoUrl 'https://gupiao.baidu.com/stock/'
StockListDataFile "StockList.dat"
StockDictDataFile "StockDict.dat"
StockDataFile "StockInfo.dat"
StockGDData "StockGD.dat"
StockGDUrl "http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CirculateStockHolder/stockid/#code.phtml"
GDDataFile "GDData.dat"
stockdict={}
StockList=[]

df pd.DataFrame(columns=  ['date''code''name''no.',"price"'cop''total''change''type'])

debug False

def debugout(str):
    if debug:
        print(str)

#取得HTML数据
def GetHTMLText(url):
    try:
        debugout("Starting get url" url)
        requests.get(url)
        r.raise_for_status()
        r.encoding r.apparent_encoding
        return r.text
    except:
        return ""

#取得股票列表——东方财富
def GetStockList():
    html GetHTMLText(StockListUrl)
    html.lower()
    page etree.HTML(s)
    if page==None:
        return
    href page.xpath('//a')
    for in href:
        try:
            i.text
            #d re.findall('"(.*")"(""[630][0]\d[4]")"',s)
            re.findall(r"[630][0]\d{4}",s)
            if len(d)>0:
                s.find(d[0])
                d1 s[0:n-1]
                if len(d1)>5:
                    continue
                StockList.append(d[0])
                stockdict.update({d[0]:d1})
        except:
            continue

    '''
    #use beautiful soup
    soup BeautifulSoup(html, 'html.parser')
    soup.find_all('a')
    for in a:
        try:
            href i.attrs['href']
            href
            StockList.append(re.findall(r"[s][hz][630][0]\d{4}"s)[0])
        except:
            continue
    return StockList
    '''
    return StockList


#取得股票当日价格——百度
def getStockInfo(lst, stockURL, fpath):
    count 0
    errCount 0
    for stock in lst:
        #重组URL
        if stock[0]=='6':
            'sh'+stock
        elif stock[0]== 's':
            stock
        else:
            'sz' stock
        url stockURL ".html"
        html GetHTMLText(url)
        try:
            if html == "":
                continue
            infoDict {}
            s=html.lower()

            page etree.HTML(s)
            if page==None:
                return
            stockInfo page.xpath('//a[@class="bets-name"]')

              name  (stockInfo[0].text)
            name name.split()[0]

            infoDict.update({'股票名称'name})

            keylist page.xpath('//div[@class="bets-content"]/div/dl/dt')
            valueList page.xpath('//div[@class="bets-content"]/div/dl/dd')

            for in range(len(keylist)):
                key keylist[i].text
                val valueList[i].text
                infoDict[key] val

            with open(fpath, 'a'encoding='utf-8'as f:
                f.write(str(infoDict) '\n')
                count count 1
                print("\r当前进度: %.2f%%   %s  Count: %d Error: %d  Name:%s" (count 100 len(lst), stock, counterrCount,name),
                      end="")
        except:
            count count 1
            errCount errCount 1
            print("\r当前进度: %.2f%%   %s  Count: %d Error: %d  Name:%s" (
            count 100 len(lst), stock, counterrCount, name),
                  end="")
            continue

#取得十大股东信息——新浪
def GetGDInfo(code,stockurl):
    =gpCode(code,False,False)
    url stockurl
    url url.replace('#code',s)
    html GetHTMLText(url)
    html.lower()
    page etree.HTML(s)
    if page == None:
        return
    #读取股票名称
    k=page.xpath('//th[@colspan="6"]')
    aName k[0].text.strip()
    aName.find('(')
    aName aName[0:i]
    aData ['date''code''name''no.',"price"'cop''total''change''type']
    aDate ""
    flag 0
    aPrice=""

    #其它股东信息
    page.xpath('//td/div[@align="center"]')
    for in k:
        xx x.xpath("./a")
        if len(xx) 0 and "name" in xx[0].attrib:
            aDate (xx[0].attrib['name'])
            ii aDate[5:7]
            if ii=="03":
                ii="1"
            elif ii=="06":
                ii="2"
            elif ii=="09":
                ii="3"
            else:
                ii="4"
            aPrice=GetJimoPrice(code,aDate[0:4],ii)
            flag 1
            continue
        x.text
        if s==None:
            continue
        s.strip()

        #排名
        if re.match("^([1-9]|10)$",s):
            #排名
            aData[0aDate
            aData[1code
            aData[2aName
            aData[3s
            aData[4aPrice
            for xxx in range(5,9):
                aData[xxx] "NA"
            flag 5
        elif flag<<span style="color:#ff0000;">9:
            aData[flag]=s
            flag+=1
        if flag>8:
            with open(GDDataFile, 'a'encoding='utf-8'as f:
                f.write(str(aData)+"\n")
            df.loc[len(df)] aData
            debugout(aData)

#取得股票季末价格
def GetJimoPrice(code,ayear,ajd):
    url StockPriceUrl
    url url.replace("#year",ayear)
    url url.replace("#jd",ajd)
    url url.replace("#code",code)
    HTML GetHTMLText(url)
    HTML.lower()
    page etree.HTML(s)
    if page == None:
        return ""
    page.xpath('//tr/td/div[@align="center"]')
    if len(x)>10:
        return x[10].text
    else:
        return ""


#处理股票代码
def gpCode(code,with_s=False,upper=False):
    code code.lower()
    if with_s:
        if code[0!= "s":
            if code[0]=="6":
                code "sh"+code
            else:
                code= "sz"+code
    else:
        if code[0]=="s":
            code code[2:]
    if upper:
        code code.upper()
    if len(code)==6 or len(code)==8:
        return code
    else:
        return ""



def main():
    debugout("Starting get stock list...")
    GetStockList()
    with open(StockListDataFile, 'w'encoding='utf-8'as f:
        f.write(str(StockList))
    with open(StockDictDataFile, 'w'encoding='utf-8'as f1:
        f1.write(str(stockdict))
    debugout("Starting get stock info......")
    icount=len(StockList)
    idx 1
    with open(GDDataFile, 'w'encoding='utf-8'as f:
        f.write(str(""))
    for in StockList:
        GetGDInfo(i,StockGDUrl)
        print ("Processing %s %d of %d"%(i,idx,icount))
        idx+=1
        time.sleep(1)#这个自己看,怎么折腾,不要被封,效率很低,如果自己有代理啥的,自己折腾个线程
        #break #时间太长,且有可能被ban 可以考虑等一秒继续
    df.to_csv(GDDataFile+".csv")
main()

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有