鏈接:http://www.p2p001.com/licai/index/id/147.html

所需獲取數據鏈接類似於:http://www.p2p001.com/licai/shownews/id/454.html:

庫:
requests (For human)
re (正則)
pandas (用來處理數據)
BeautifulSoup (用來解析網頁文本)
此次抓取邏輯思維在代碼之后
上代碼:
#coding utf-8 import requests import re import pandas from bs4 import BeautifulSoup user_agent = 'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)' headers = {'User-Agent':user_agent} #定義函數,得到每日報的鏈接,並以列表形式返回 def get_newsurl(): newsurl=[] url1='http://www.p2p001.com/licai/index/id/147/p/' num=1 url2='.html' while num<=22: url=url1+str(num)+url2 try: r1=requests.get(url,headers=headers) except: print ('wrong %s' % url) else: s1=BeautifulSoup(r1.text,'lxml') for x in s1.find_all(href=re.compile('licai/shownews')): newsurl.append(x['href']) num=num+1 return newsurl #定義函數,得到的數據,以字典形式返回 def get_info(): url='http://www.p2p001.com' date=[] zonghe=[] one=[] one_three=[] three_six=[] six_twelve=[] twelve_most=[] for y in get_newsurl(): try: main_url=url+y r2=requests.get(main_url,headers=headers) except: print ('wrong %s' % main_url) else: s2=BeautifulSoup(r2.text,'lxml') date.append(s2.find(text=re.compile('統計日期'))[5:]) rate=s2.find_all('td') zonghe.append(rate[10].string) one.append(rate[11].string) one_three.append(rate[12].string) three_six.append(rate[13].string) six_twelve.append(rate[14].string) twelve_most.append(rate[15].string) p={'Date':date, '綜合':zonghe, '1個月':one, '1-3個月':one_three, '3-6個月':three_six, '6-12個月':six_twelve, '12個月及以上':twelve_most} return p #pandas存儲數據 p=pd.DataFrame(get_info())
p.to_csv('f://1//rate1.csv',index=False,
columns=['Date','綜合','1個月','1-3個月','3-6個月','6-12個月','12個月及以上'],
header=['Date','綜合','1個月','1-3個月','3-6個月','6-12個月','12個月及以上'])

此次學習總結及反思:
1.為了方便處理,並沒有使用數據庫來存儲數據,而是使用pandas將數據以csv格式保存在本地硬盤F
2.定義第一個函數對象get_newsurl,以列表形式返回理財指數日報鏈接,第二個函數遍歷第一個函數的返回值,進行數據的采集
3.為什么不將pandas的一系列操作放在函數對象get_info中,從而直接完成一系列的操作呢?
當時考慮了效率和靈活性考慮。
one:如果將pandas的數據操作丟在get_info中,那么調用get_info()的時候,整個效率將會降低很多很多
two:拿出來單獨處理,靈活性大大提高,調用get_info(),以字典形式返回我需要的數據,拿到這個數據后,我可以做任何我想做的處理,而不是用一個函數將整個采集下來的數據直接打入地牢,讓這些數據沒有了自由。
4.抓取思路
①先發現日報的鏈接規律,也就是說共有22頁,每頁20份日報指數數據,因為只做一次簡單的抓取,所以這個值這個可以寫死
這個就是第一個函數做的事,返回這些href的值
②進入具體的日報頁面,抓取我們所需要的數據,並以字典形式返回
③處理並存儲數據(pandas)
注明:數據來源於第一網貸http://www.p2p001.com/
小白一枚,能力有限,做的不好的地方,尤其是邏輯與思維上的東西,需要大神們看到了多多指教和斧正
buddyquan。
QQ:1749061919 小白爬蟲求帶
