Python中怎么爬取金融市場數(shù)據(jù)

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)Python中怎么爬取金融市場數(shù)據(jù),文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

超過十多年行業(yè)經(jīng)驗,技術(shù)領(lǐng)先,服務(wù)至上的經(jīng)營模式,全靠網(wǎng)絡(luò)和口碑獲得客戶,為自己降低成本,也就是為客戶降低成本。到目前業(yè)務(wù)范圍包括了:網(wǎng)站設(shè)計制作、成都網(wǎng)站設(shè)計,成都網(wǎng)站推廣,成都網(wǎng)站優(yōu)化,整體網(wǎng)絡(luò)托管,小程序定制開發(fā),微信開發(fā),app軟件開發(fā)公司,同時也可以讓客戶的網(wǎng)站和網(wǎng)絡(luò)營銷和我們一樣獲得訂單和生意!

1、正則表達(dá)式

具體的詳細(xì)介紹可自行去網(wǎng)上補(bǔ)知識,這里只介紹一些規(guī)則和常用的用法。

# 正則表達(dá)式 規(guī)則:     單字符:             .  : 除換行以外所有字符             [] : 匹配集合中任意一個字符             \d : 數(shù)字             \D : 非數(shù)字             \w : 數(shù)字、字母、下劃線、中文             \W : 非數(shù)字、字母、下劃線、中文             \s : 空格             \S : 非空格     數(shù)量修飾:              * : 任意多次              + : 至少1次              ?: 非貪婪方式,可有可無            {m} : 固定m次           {m+} : 至少m次          {m,n} : m到n次     起始:              ^ : 以啥啥開頭              $ : 以啥啥結(jié)尾     常用組合和函數(shù):             .* : 貪婪方式任意字符任意次數(shù)            .*? : 非貪婪方式任意字符任意次數(shù)            r = re.compile(r'正則表達(dá)式',re.S) :                                最常用:將規(guī)則傳遞給某個參數(shù)以便反復(fù)使用            re.match\re.search\(字符串)            re.findall(字符串)            re.sub(正則表達(dá)式,替換內(nèi)容,字符串)

2、bs4

同樣,詳細(xì)知識自行補(bǔ),這里只介紹常用的用法:select結(jié)合選擇器的用法。

# bs4用法 首先加載里面的BeautifulSoup: from bs4 import BeautifulSoup soup = BeautifulSoup('網(wǎng)頁響應(yīng)回來的東西')

主要有以下幾種提取規(guī)則:

1、獲取標(biāo)簽     soup.a   獲取a標(biāo)簽(***個) 2、獲取屬性     soup.a.attrs   獲取a標(biāo)簽下所有的屬性和值,返回的是字典     soup.a['name'] 獲取a標(biāo)簽下的name屬性 3、獲取內(nèi)容     soup.a.string()     soup.a.text()   建議使用這個 4、find用法     soup.find('a')  找到***個a     soup.find('a',title='')  附加條件的查找 5、find_all用法     soup.find_all('a')  找到所有a     soup.find_all(['a','b']) 找到所有a和b     soup.find_all('a',limit=5) 找到前5個a 6、select用法——重點     結(jié)合選擇器使用,常用的選擇器如下:     標(biāo)簽選擇器:如div表示為div     類選擇器:.表示,如class = 'you'表示為.you     id選擇器:#表示,如id = 'me'表示為#me     組合選擇器:如div,.you,#me       層級選擇器:如div .you #me表示選取div標(biāo)簽下的you類下的id為me的內(nèi)容               再如div > .you > #me,> 則表示只能是下面一級

三、開始實戰(zhàn)——爬取某信托網(wǎng)的信托在售數(shù)據(jù)

1、爬取前的準(zhǔn)備工作——梳理好代碼的邏輯

正如前面所說,寫代碼之前,首先要清楚你想要干什么,如果是你,你是什么樣的動作來達(dá)到你的這個目的或意圖。

***,你的目的或意圖是什么,對于本例而言,我需要獲取任意某頁至某頁信托在售產(chǎn)品的下面數(shù)據(jù):產(chǎn)品名稱、發(fā)行機(jī)構(gòu)、發(fā)行時間、***收益、產(chǎn)品期限、投資行業(yè)、發(fā)行地、收益分配方式、發(fā)行規(guī)模、***收益、***收益和利率等級劃分情況這12個數(shù)據(jù)。

第二,如果是人,需要哪些動作來達(dá)到這個目的。我們來看下網(wǎng)頁。動作就清晰了:

輸入網(wǎng)址/搜索關(guān)鍵字 > 進(jìn)入網(wǎng)站 > 點擊紅色框框里的信托產(chǎn)品和在售 > 錄入下面綠色框框里的相關(guān)信息 >  發(fā)現(xiàn)信息不全,再點擊這個產(chǎn)品,在詳情頁(再下一張圖)繼續(xù)錄入。

Python中怎么爬取金融市場數(shù)據(jù)

Python中怎么爬取金融市場數(shù)據(jù)

2、開始爬取

既然動作清晰了,那就可以讓計算機(jī)來模擬人的這個動作進(jìn)行爬取了。

然后就是寫代碼的邏輯了。我們用做數(shù)學(xué)題常用的倒推法來梳理這個過程。

要想獲取數(shù)據(jù) < 你得解析網(wǎng)頁給你的響應(yīng) < 你得有個響應(yīng) < 你得發(fā)送請求 < 你得有個請求request <  你得有個url。

然后我們再正過來解題:獲取url > 構(gòu)建request > 發(fā)送請求 > 獲取響應(yīng) > 解析響應(yīng) > 獲取所需數(shù)據(jù)  > 保存數(shù)據(jù)。

所以按照這個步驟,我們可以先做出一個大框架,然后在框架的基礎(chǔ)上補(bǔ)充血肉。大框架,就是定義個主函數(shù)。

值得注意的是,本例中,每個產(chǎn)品的信息獲取,我們都有二次點擊的動作,即***頁數(shù)據(jù)不全,我們再點擊進(jìn)入詳情頁進(jìn)行剩余數(shù)據(jù)的獲取,因此,本例是有兩層的數(shù)據(jù)獲取過程的。***層使用正則表達(dá)式,第二層使用bs4。

① 定義主函數(shù)

如下是這個主函數(shù),前面的寫入相關(guān)數(shù)據(jù)你可以先不管,這都是在***步的獲取url時,后補(bǔ)過來的。

回到前面的目的:提取任意某頁至任意某頁的數(shù)據(jù),所以寫個循環(huán)是必須的,然后在循環(huán)下方,兩層網(wǎng)頁的數(shù)據(jù)獲取框架就出來了。(由于第二層網(wǎng)頁的url是根據(jù)***層網(wǎng)頁的某個數(shù)據(jù)拼接出來的,而***層網(wǎng)頁是一下子提取整個頁面所有產(chǎn)品的信息,所以第二層網(wǎng)頁的提取也設(shè)置了個循環(huán),對***層網(wǎng)頁的所有產(chǎn)品,一個一個點進(jìn)去進(jìn)行提取)

# 定義一個主函數(shù) def main():      # 寫入相關(guān)數(shù)據(jù)     url_1 = 'http://www.某信托網(wǎng).com/Action/ProductAJAX.ashx?'     url_2 = 'http://www.某信托網(wǎng)/Product/Detail.aspx?'     size = input('請輸入每頁顯示數(shù)量:')     start_page = int(input('請輸入起始頁碼:'))     end_page = int(input('請輸入結(jié)束頁碼'))     type = input('請輸入產(chǎn)品類型(1代表信托,2代表資管):')       items = []                # 定義一個空列表用來存儲數(shù)據(jù)      # 寫循環(huán)爬取每一頁     for page in range(start_page, end_page + 1):      # ***層網(wǎng)頁的爬取流程         print('第{}頁開始爬取'.format(page))          # 1、拼接url&mdash;&mdash;可定義一個分函數(shù)1:joint         url_new = joint(url_1 ,size=size ,page=page ,type=type)          # 2、發(fā)起請求,獲取響應(yīng)&mdash;&mdash;可定義一個分函數(shù)2:que_res         response = que_res(url_new)          # 3、解析內(nèi)容,獲取所需數(shù)據(jù)&mdash;&mdash;可定義一個分函數(shù)3:parse_content_1         contents = parse_content_1(response)          # 4、休眠2秒         time.sleep(2)      # 第二層網(wǎng)頁的爬取流程          for content in contents:             print('    第{}頁{}開始下載'.format(page ,content[0]))              # 1、拼接url             id = content[0]             url_2_new = joint(url_2 ,id=id)      # joint為前面定義的第1個函數(shù)              # 2、發(fā)起請求,獲取響應(yīng)             response_2 = que_res(url_2_new)     # que_res為前面定義的第2個函數(shù)              # 3、解析內(nèi)容,獲取所需數(shù)據(jù)&mdash;&mdash;可定義一個分函數(shù)4:parse_content_2,直接返回字典格式的數(shù)據(jù)             item = parse_content_2(response_2 ,content)              # 存儲數(shù)據(jù)             items.append(item)             print('    第{}頁{}結(jié)束下載'.format(page ,content[0]))              # 休眠5秒             time.sleep(5)          print('第{}頁結(jié)束爬取'.format(page))      # 保存數(shù)據(jù)為dataframe格式CSV文件     df = pd.DataFrame(items)     df.to_csv('data.csv' ,index=False ,sep=',' ,encoding='utf-8-sig')     print('*'*30)    print('全部爬取結(jié)束')  if __name__ == '__main__':     main()

② 獲取url &mdash;&mdash; ***層和第二層通用

由于我們需要訪問兩層的數(shù)據(jù),所以希望定義一個函數(shù),能對兩層的URL都可以進(jìn)行拼接。

如下圖為***層頁面的內(nèi)容和源碼,由第二個紅框中的內(nèi)容(X-Requested-With:XMLHttpRequest),可知這是一個AJAX  get請求,且攜帶者第三個紅框中的數(shù)據(jù),而第三個紅框中的數(shù)據(jù),又恰好是***個紅框中的url的一部分,即為:

http://www.某信托網(wǎng).com/Action/ProductAJAX.ashx?加上第三個紅框中的數(shù)據(jù)。

第三個框框中包括幾個可變的數(shù)據(jù):pageSize(表示一頁顯示多少產(chǎn)品);pageIndex(表示第幾頁);conditionStr(定義產(chǎn)品類型,1表示信托,2表示資管),其余的數(shù)據(jù)都是固定的(這其中有個_:1544925791285這種下劃線帶一串?dāng)?shù)字的東西,像是個隨機(jī)數(shù),去掉也沒影響,我就給去掉了)。

Python中怎么爬取金融市場數(shù)據(jù)

下圖為第二層頁面的內(nèi)容和源碼,可見只是一個簡單的get請求,且網(wǎng)址很簡單,就是一個http://www.某信托網(wǎng).com/Product/Detail.aspx?加上一個id,而這個id又來自哪里呢,答案就在***層網(wǎng)頁的響應(yīng)數(shù)據(jù)中(見再下面一幅圖的紅色框)。

Python中怎么爬取金融市場數(shù)據(jù)

Python中怎么爬取金融市場數(shù)據(jù)

通過上面的分析,***層網(wǎng)頁的請求url由一個固定的部分加上一些數(shù)據(jù),第二層網(wǎng)頁的url依賴于***層的數(shù)據(jù),我們先在主函數(shù)中將url_1、url_2和一些可變的數(shù)據(jù)寫入(見上面的主函數(shù)),然后定義一個函數(shù)用來拼接兩層的url即可,因為***層網(wǎng)頁url的固定部分長度為47,第二層的為43,這里使用一個長度條件來判斷是拼接***層還是拼接第二層。

# 定義第1個分函數(shù)joint,用來拼接url def joint(url,size=None,page=None,type=None,id=None):     if len(url) > 45:         condition = 'producttype:' + type + '|status:在售'         data = {         'mode': 'statistics',         'pageSize': size,         'pageIndex': str(page),         'conditionStr': condition,         'start_released': '',         'end_released': '',         'orderStr': '1',         'ascStr': 'ulup'         }         joint_str = urllib.parse.urlencode(data)         url_new = url + joint_str     else:         data = {             'id':id             }         joint_str = urllib.parse.urlencode(data)         url_new = url + joint_str     return url_new

③ 構(gòu)建request + 獲取response一條龍 &mdash;&mdash; ***層和第二層通用

獲取url后,接下來就是構(gòu)建request用來發(fā)送請求獲取響應(yīng)了,此處定義一個函數(shù)實現(xiàn)一條龍服務(wù)。

這里為了提防反爬,user_agent在多個里隨機(jī)選,并使用了代理池(雖然不多),并且我電腦端也進(jìn)行了局域網(wǎng)ip代理。

# 定義第2個函數(shù)que_res,用來構(gòu)建request發(fā)送請求,并返回響應(yīng)response def que_res(url):      # 構(gòu)建request的***步&mdash;&mdash;構(gòu)建頭部:headers     USER_AGENTS = [          "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",         "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",         ]     user_agent = random.choice(USER_AGENTS)     headers = {         'Accept-Language': 'zh-CN,zh;q=0.8',         'Connection': 'keep-alive',          'Host': 'www.某信托網(wǎng).com',         'Referer': 'http://www.某信托網(wǎng).com/Product/Index.aspx',         'User-Agent': user_agent,         'X-Requested-With': 'XMLHttpRequest'         }      # 構(gòu)建request的第二步&mdash;&mdash;構(gòu)建request     request = urllib.request.Request(url=url, headers=headers)       # 發(fā)起請求的***步&mdash;&mdash;構(gòu)建代理池     proxy_list = [               {'http':'125.40.29.100:8118'},         {'http':'14.118.135.10:808'}         ]     proxy = random.choice(proxy_list)      # 發(fā)起請求的第二步&mdash;&mdash;創(chuàng)建handler和opener     handler = urllib.request.ProxyHandler(proxy)     opener = urllib.request.build_opener(handler)      # 發(fā)起請求的第三步&mdash;&mdash;發(fā)起請求,獲取響應(yīng)內(nèi)容并解碼     response = opener.open(request).read().decode()      # 返回值     return response

④ 解析***層網(wǎng)頁的內(nèi)容

獲取響應(yīng)之后就是解析并提取數(shù)據(jù)了,***層使用正則表達(dá)式的方法來進(jìn)行。

獲取的response如下如:

Python中怎么爬取金融市場數(shù)據(jù)

因此可寫出如下正則,從左到右分配匹配出ID、產(chǎn)品名稱、發(fā)行機(jī)構(gòu)、發(fā)行時間、產(chǎn)品期限、投資行業(yè)、首頁收益。

# 定義第3個函數(shù)parse_content_1,用來解析并匹配***層網(wǎng)頁內(nèi)容,此處使用正則表達(dá)式方法 def parse_content_1(response):      # 寫正則進(jìn)行所需數(shù)據(jù)的匹配     re_1 = re.compile(     r'{"ROWID".*?"ID":"(.*?)","Title":"(.*?)","producttype".*?"issuers":"(.*?)","released":"(.*?) 0:00:00","PeriodTo":(.*?),"StartPrice".*?"moneyinto":"(.*?)","EstimatedRatio1":(.*?),"status":.*?"}')     contents = re_1.findall(response)     return contents

⑤ 解析第二層網(wǎng)頁的內(nèi)容并輸出數(shù)據(jù)

第二層使用bs4中的select+選擇器的方法來進(jìn)行。除了***層所提取的數(shù)據(jù)外,還需要發(fā)行地、收益分配方式、發(fā)行規(guī)模、***收益、***收益和利率等級分布情況。

網(wǎng)頁如下,可見,我們所需要的信息隱藏在一個又一個tr標(biāo)簽里,而這個tr標(biāo)簽處于id=“procon1”下的一個table標(biāo)簽里(此處有個坑,就是從網(wǎng)頁來看,table下還有個tbody標(biāo)簽,而實際得到的響應(yīng)里并沒有)。

Python中怎么爬取金融市場數(shù)據(jù)

由于我們不是所有的信息都要,所以我們可以一個一個的提取,最終輸出個數(shù)據(jù)。代碼如下(這中間用到了前面提到的選擇器知識和一些字符串處理方法):

# 定義第4個函數(shù)parse_content_2,用來解析并匹配第二層網(wǎng)頁內(nèi)容,并輸出數(shù)據(jù),此處使用BeautifulSoup方法 def parse_content_2(response,content):      # 使用bs4進(jìn)行爬取第二層信息     soup = BeautifulSoup(response)      # 爬取發(fā)行地和收益分配方式,該信息位于id為procon1下的table下的第4個tr里     tr_3 = soup.select('#procon1 > table > tr')[3] address = tr_3.select('.pro-textcolor')[0].text r_style = tr_3.select('.pro-textcolor')[1].text       # 爬取發(fā)行規(guī)模,該信息位于id為procon1下的table下的第5個tr里     tr_4 = soup.select('#procon1 > table > tr')[4] guimo = tr_4.select('.pro-textcolor')[1].text re_2 = re.compile(r'.*?(\d+).*?', re.S)      scale = re_2.findall(guimo)[0]    # 爬取收益率,該信息位于id為procon1下的table下的第8個tr里     tr_7 = soup.select('#procon1 > table > tr')[7] rate = tr_7.select('.pro-textcolor')[0].text[:(-1)] r = rate.split('至')   r_min = r[0]     r_max = r[1]      # 提取利率等級     tr_11 = soup.select('#procon1 > table > tr')[11] r_grade = tr_11.select('p')[0].text      # 保存數(shù)據(jù)到一個字典中     item = {     '產(chǎn)品名稱':content[1],     '發(fā)行機(jī)構(gòu)':content[2],     '發(fā)行時間':content[3],     '產(chǎn)品期限':content[4],     '投資行業(yè)':content[5],     '首頁收益':content[6],     '發(fā)行地': address,     '收益分配方式': r_style,     '發(fā)行規(guī)模': scale,     '***收益': r_min,     '***收益': r_max,     '利率等級': r_grade     }      # 返回數(shù)據(jù)     return item

⑥ 保存數(shù)據(jù)到本地(以dataframe格式保存到本地CSV格式)

# 保存數(shù)據(jù)為dataframe格式CSV文件     df = pd.DataFrame(items)     df.to_csv('data.csv',index=False,sep=',',encoding='utf-8-sig')  好了,現(xiàn)在就大功告成了,***不要只讓自己爽,也要讓對方的服務(wù)器別太難過,在一些地方休眠幾秒,完整代碼如下。  import urllib.request import urllib.parse import re import random from bs4 import BeautifulSoup import pandas as pd import time  # 定義第1個分函數(shù)joint,用來拼接url def joint(url,size=None,page=None,type=None,id=None):     if len(url) > 45:         condition = 'producttype:' + type + '|status:在售'         data = {         'mode': 'statistics',         'pageSize': size,         'pageIndex': str(page),         'conditionStr': condition,         'start_released': '',         'end_released': '',         'orderStr': '1',         'ascStr': 'ulup'         }         joint_str = urllib.parse.urlencode(data)         url_new = url + joint_str     else:         data = {             'id':id             }         joint_str = urllib.parse.urlencode(data)         url_new = url + joint_str     return url_new  # 定義第2個函數(shù)que_res,用來構(gòu)建request發(fā)送請求,并返回響應(yīng)response def que_res(url):      # 構(gòu)建request的***步&mdash;&mdash;構(gòu)建頭部:headers     USER_AGENTS = [          "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",         "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",         "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",         ]     user_agent = random.choice(USER_AGENTS)     headers = {         'Accept-Language': 'zh-CN,zh;q=0.8',         'Connection': 'keep-alive',          'Host': 'www.某信托網(wǎng).com',         'Referer': 'http://www.某信托網(wǎng).com/Product/Index.aspx',         'User-Agent': user_agent,         'X-Requested-With': 'XMLHttpRequest'         }      # 構(gòu)建request的第二步&mdash;&mdash;構(gòu)建request     request = urllib.request.Request(url=url, headers=headers)       # 發(fā)起請求的***步&mdash;&mdash;構(gòu)建代理池     proxy_list = [               {'http':'125.40.29.100:8118'},         {'http':'14.118.135.10:808'}         ]     proxy = random.choice(proxy_list)      # 發(fā)起請求的第二步&mdash;&mdash;創(chuàng)建handler和opener     handler = urllib.request.ProxyHandler(proxy)     opener = urllib.request.build_opener(handler)      # 發(fā)起請求的第三步&mdash;&mdash;發(fā)起請求,獲取響應(yīng)內(nèi)容并解碼     response = opener.open(request).read().decode()      # 返回值     return response  # 定義第3個函數(shù)parse_content_1,用來解析并匹配***層網(wǎng)頁內(nèi)容,此處使用正則表達(dá)式方法 def parse_content_1(response):      # 寫正則進(jìn)行所需數(shù)據(jù)的匹配     re_1 = re.compile(     r'{"ROWID".*?"ID":"(.*?)","Title":"(.*?)","producttype".*?"issuers":"(.*?)","released":"(.*?) 0:00:00","PeriodTo":(.*?),"StartPrice".*?"moneyinto":"(.*?)","EstimatedRatio1":(.*?),"status":.*?"}')     contents = re_1.findall(response)     return contents  # 定義第4個函數(shù)parse_content_2,用來解析并匹配第二層網(wǎng)頁內(nèi)容,并輸出數(shù)據(jù),此處使用BeautifulSoup方法 def parse_content_2(response,content):      # 使用bs4進(jìn)行爬取第二層信息     soup = BeautifulSoup(response)      # 爬取發(fā)行地和收益分配方式,該信息位于id為procon1下的table下的第4個tr里     tr_3 = soup.select('#procon1 > table > tr')[3]         #select到第四個目標(biāo)tr     address = tr_3.select('.pro-textcolor')[0].text        #select到該tr下的class為pro-textcolor的***個內(nèi)容(發(fā)行地)     r_style = tr_3.select('.pro-textcolor')[1].text        #select到該tr下的class為pro-textcolor的第二個內(nèi)容(收益分配方式)      # 爬取發(fā)行規(guī)模,該信息位于id為procon1下的table下的第5個tr里     tr_4 = soup.select('#procon1 > table > tr')[4]         #select到第五個目標(biāo)tr         guimo = tr_4.select('.pro-textcolor')[1].text          #select到該tr下的class為pro-textcolor的第二個內(nèi)容(發(fā)行規(guī)模:至***萬)     re_2 = re.compile(r'.*?(\d+).*?', re.S)                #設(shè)立一個正則表達(dá)式,將純數(shù)字提取出來     scale = re_2.findall(guimo)[0]                         #提取出純數(shù)字的發(fā)行規(guī)模      # 爬取收益率,該信息位于id為procon1下的table下的第8個tr里     tr_7 = soup.select('#procon1 > table > tr')[7]         #select到第八個目標(biāo)tr     rate = tr_7.select('.pro-textcolor')[0].text[:(-1)]    #select到該tr下的class為pro-textcolor的***個內(nèi)容(且通過下標(biāo)[-1]將末尾的 % 去除)     r = rate.split('至')                                   #此處用來提取***收益和***收益     r_min = r[0]     r_max = r[1]      # 提取利率等級     tr_11 = soup.select('#procon1 > table > tr')[11]       #select到第十二個目標(biāo)tr     r_grade = tr_11.select('p')[0].text                    #select到該tr下的p下的***個內(nèi)容(即利率等級)      # 保存數(shù)據(jù)到一個字典中     item = {     '產(chǎn)品名稱':content[1],     '發(fā)行機(jī)構(gòu)':content[2],     '發(fā)行時間':content[3],     '產(chǎn)品期限':content[4],     '投資行業(yè)':content[5],     '首頁收益':content[6],     '發(fā)行地': address,     '收益分配方式': r_style,     '發(fā)行規(guī)模': scale,     '***收益': r_min,     '***收益': r_max,     '利率等級': r_grade     }      # 返回數(shù)據(jù)     return item  # 定義一個主函數(shù) def main():      # 寫入相關(guān)數(shù)據(jù)     url_1 = 'http://www.某信托網(wǎng).com/Action/ProductAJAX.ashx?'     url_2 = 'http://www.某信托網(wǎng).com/Product/Detail.aspx?'     size = input('請輸入每頁顯示數(shù)量:')     start_page = int(input('請輸入起始頁碼:'))     end_page = int(input('請輸入結(jié)束頁碼'))     type = input('請輸入產(chǎn)品類型(1代表信托,2代表資管):')      items = []                       # 定義一個空列表用來存儲數(shù)據(jù)      # 寫循環(huán)爬取每一頁     for page in range(start_page, end_page + 1):          # ***層網(wǎng)頁的爬取流程         print('第{}頁開始爬取'.format(page))         # 1、拼接url&mdash;&mdash;可定義一個分函數(shù)1:joint         url_new = joint(url_1,size=size,page=page,type=type)          # 2、發(fā)起請求,獲取響應(yīng)&mdash;&mdash;可定義一個分函數(shù)2:que_res         response = que_res(url_new)          # 3、解析內(nèi)容,獲取所需數(shù)據(jù)&mdash;&mdash;可定義一個分函數(shù)3:parse_content_1         contents = parse_content_1(response)          # 4、休眠2秒         time.sleep(2)          # 第二層網(wǎng)頁的爬取流程          for content in contents:             print('    第{}頁{}開始下載'.format(page,content[0]))             # 1、拼接url             id = content[0]             url_2_new = joint(url_2,id=id)      # joint為前面定義的第1個函數(shù)              # 2、發(fā)起請求,獲取響應(yīng)             response_2 = que_res(url_2_new)     # que_res為前面定義的第2個函數(shù)              # 3、解析內(nèi)容,獲取所需數(shù)據(jù)&mdash;&mdash;可定義一個分函數(shù)4:parse_content_2,直接返回字典格式的數(shù)據(jù)             item = parse_content_2(response_2,content)              # 存儲數(shù)據(jù)             items.append(item)             print('    第{}頁{}結(jié)束下載'.format(page,content[0]))             # 休眠5秒             time.sleep(5)          print('第{}頁結(jié)束爬取'.format(page))       # 保存數(shù)據(jù)為dataframe格式CSV文件     df = pd.DataFrame(items)     df.to_csv('data.csv',index=False,sep=',',encoding='utf-8-sig')      print('*'*30)     print('全部爬取結(jié)束')  if __name__ == '__main__':     main()

3、爬取結(jié)果

運行代碼,這里以每頁顯示4個產(chǎn)品,爬取前3頁的信托在售為例,運行結(jié)果如下:

Python中怎么爬取金融市場數(shù)據(jù)

然后打開存到本地的CSV文件如下:結(jié)果是美好的。

Python中怎么爬取金融市場數(shù)據(jù)

上述就是小編為大家分享的Python中怎么爬取金融市場數(shù)據(jù)了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)站名稱:Python中怎么爬取金融市場數(shù)據(jù)
文章來源:http://muchs.cn/article6/ihgpog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)、定制開發(fā)、電子商務(wù)、品牌網(wǎng)站建設(shè)網(wǎng)頁設(shè)計公司、軟件開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站