-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFund Web Crawler.py
213 lines (176 loc) · 6.68 KB
/
Fund Web Crawler.py
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
# -*- coding: utf-8 -*-
"""基金.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1-pQOqH5Nd9xTB3o3-F0Zff1xFxxJV3a9
"""
!pip install pandas
!pip install requests
!pip install beautifulsoup4
"""#爬數量"""
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re
def post(YM, total):
url = 'https://www.sitca.org.tw/ROC/Industry/IN2629.aspx'
with requests.Session() as s:
page = s.get(url)
soup = BeautifulSoup(page.content, 'lxml')
payload_loginPage = {
"ctl00$ContentPlaceHolder1$ddlQ_YM" : YM,
"ctl00$ContentPlaceHolder1$rdo1" : "rbClass",
"ctl00$ContentPlaceHolder1$ddlQ_Class" : "AA1",
"ctl00$ContentPlaceHolder1$BtnQuery" : "查詢"
}
payload_loginPage["__VIEWSTATE"] = soup.select_one("#__VIEWSTATE")["value"]
payload_loginPage["__VIEWSTATEGENERATOR"] = soup.select_one("#__VIEWSTATEGENERATOR")["value"]
payload_loginPage["__EVENTVALIDATION"] = soup.select_one("#__EVENTVALIDATION")["value"]
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'}
ss = s.post(url, data=payload_loginPage, headers = headers)
soup = BeautifulSoup(ss.content, 'lxml')
DTeven = soup.select(".DTeven")
DTodd = soup.select(".DTodd")
#data1
DT_m1=[]
for DT in DTeven:
match_result = re.match(r'<td align="left" class="DTeven">(.*)</td>', str(DT), re.I)
if match_result!=None:
m = match_result.group(1)
if m:
DT_m1.append(m.encode('raw_unicode_escape').decode())
DTSum1=[DT_m1[dtm] for dtm in range(len(DT_m1)) if dtm%3==2 and DT_m1[dtm-2]=="國內上市"]
#data2
DT_m2=[]
for DT in DTodd:
match_result = re.match(r'<td align="left" class="DTodd">(.*)</td>', str(DT), re.I)
if match_result!=None:
m = match_result.group(1)
if m:
DT_m2.append(m.encode('raw_unicode_escape').decode())
DTSum2=[DT_m2[dtm] for dtm in range(len(DT_m2)) if dtm%3==2 and DT_m2[dtm-2]=="國內上市"]
#合併
DTSum = DTSum1+DTSum2
#小計
print(DTSum)
for sum in DTSum:
if sum in total:
total[sum] += 1
else:
total[sum] = 1
#print(total)
#執行畫面
total={}
YM="202111"
post(YM, total)
data=[]
for n,v in sorted(total.items(),key=lambda x:x[1],reverse=True):
sv=[]
sv.append(n)
sv.append(v)
data.append(sv)
df = pd.DataFrame(data,columns=['投資標的','數量總計'])
df.to_excel(YM+'.xlsx')
df
"""#爬全部資料"""
from operator import index
def post2(YM):
url = 'https://www.sitca.org.tw/ROC/Industry/IN2629.aspx'
with requests.Session() as s:
page = s.get(url)
soup = BeautifulSoup(page.content, 'lxml')
payload_loginPage = {
"ctl00$ContentPlaceHolder1$ddlQ_YM" : YM,
"ctl00$ContentPlaceHolder1$rdo1" : "rbClass",
"ctl00$ContentPlaceHolder1$ddlQ_Class" : "AA1",
"ctl00$ContentPlaceHolder1$BtnQuery" : "查詢"
}
payload_loginPage["__VIEWSTATE"] = soup.select_one("#__VIEWSTATE")["value"]
payload_loginPage["__VIEWSTATEGENERATOR"] = soup.select_one("#__VIEWSTATEGENERATOR")["value"]
payload_loginPage["__EVENTVALIDATION"] = soup.select_one("#__EVENTVALIDATION")["value"]
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'}
ss = s.post(url, data=payload_loginPage, headers = headers)
soup = BeautifulSoup(ss.content, 'lxml')
DTeven = soup.select(".DTeven")
DTodd = soup.select(".DTodd")
#data1
name=[]
DT_m1=[]
DT1=[]
i=1
for DT in DTeven:
match_result = re.match(r'<td align="[a-z]*" class="DTeven">(.*)</td>', str(DT), re.I)
if match_result!=None:
m1 = match_result.group(1)
if m1:
DT_m1.append(m1.encode('raw_unicode_escape').decode())
i+=1
if i>7:
DT1.append(DT_m1)
i=1
DT_m1=[]
match = re.match(r'<td align="left" class="DTeven" rowspan="10">(.*)</td>', str(DT), re.I)
if match!=None:
m2 = match.group(1)
if m2:
for k in range(10):
name.append(m2.encode('raw_unicode_escape').decode())
#data2
DT_m2=[]
DT2=[]
j=1
for DT in DTodd:
match_result = re.match(r'<td align="[a-z]*" class="DTodd">(.*)</td>', str(DT), re.I)
if match_result!=None:
m = match_result.group(1)
if m:
DT_m2.append(m.encode('raw_unicode_escape').decode())
j+=1
if j>7:
DT2.append(DT_m2)
j=1
DT_m2=[]
#合併
DTSum = []
for i in range(len(DT1)):
DTSum.append(DT1[i])
DTSum.append(DT2[i])
df = pd.DataFrame(data=DTSum,columns=['名次','標的種類','標的代號','標的名稱','金額','受益權單位數','占基金淨資產價值之比例(%)'])
df['基金名稱'] = name
df['年'] = YM[0:4]
df['月'] = YM[4:6]
df2 = df[['年','月','基金名稱','標的代號','標的名稱','金額','占基金淨資產價值之比例(%)']]
df2['年'] = df2['年'].astype('int')
df2['月'] = df2['月'].astype('int')
df2['基金名稱'] = df2['基金名稱'].astype('string')
df2['標的代號'] = df2['標的代號'].astype('string')
df2['標的名稱'] = df2['標的名稱'].astype('string')
df2['金額'] = df2['金額'].str.replace(',','').astype('int')
df2['占基金淨資產價值之比例(%)'] = df2['占基金淨資產價值之比例(%)'].astype('float')
#df2.set_index('年', inplace=True)
df2.to_csv('基金.csv',encoding='utf-8-sig')
return df2
df = post2("202111")
df
df.info()
for d in range(len(df['年'])):
print(f"INSERT INTO {'基金'} VALUES ({df['年'][d]},{df['月'][d]},N'{df['基金名稱'][d]}','{df['標的代號'][d]}',{df['金額'][d]},{df['占基金淨資產價值之比例(%)'][d]});")
"""#股票名稱加代號"""
import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
res = requests.get("https://isin.twse.com.tw/isin/class_main.jsp?owncode=&stockname=&isincode=&market=1&issuetype=1&industry_code=&Page=1&chklike=Y")
df1 = pd.read_html(res.text)[0]
df1 = df1.drop(index=[0])
res = requests.get("https://isin.twse.com.tw/isin/class_main.jsp?owncode=&stockname=&isincode=&market=2&issuetype=4&industry_code=&Page=1&chklike=Y")
df2 = pd.read_html(res.text)[0]
df2 = df2.drop(index=[0])
df_name = list(df1[3])+list(df2[3])
df_val = list(df1[2])+list(df2[2])
df = pd.DataFrame(df_val,columns=['標的代號'])
df['標的名稱'] = df_name
df.to_csv('標的.csv',encoding='utf-8-sig')
df
for d in range(len(df['標的代號'])):
print(f"INSERT INTO 標的 VALUES ({df['標的代號'][d]},N'{df['標的名稱'][d]}');")