note:一:簡單爬蟲的基本步驟
1.爬蟲的前奏:
(1)明確目的
(2)找到資料對應的網頁
(3)分析網頁的結構,找到資料的位置
2.爬蟲第二步:__fetch_content方法
模擬http請求,向伺服器傳送這個請求,獲取伺服器返回給我們的html
用正規表示式提取我們要的資料
3.爬蟲第三步:__analysis
(1)找到乙個定位標籤或者是識別符號,利用正規表示式找到需要的內容:
它的選擇原則是:
唯一原則、就近原則、選擇父級閉合標籤
(2)再找到的內容中進一步提取需要的資料,可能多次提取
4.精煉提取到的資料
利用lambda表示式替換for迴圈
5.處理精煉後的資料
5.顯示處理後的資料
二:程式規範
1.注釋
2.空行的利用
3.函式大小10-20行
4.寫平級方法並用主方法呼叫,避免多級巢狀方法!
四:補充
beautiful soup, scrapy爬蟲框架
爬蟲、反爬蟲、反反爬蟲
ip 被封 **ip
五:總結
(1)加強對正規表示式的練習
(2)加強對lambda表示式的練習!
(3)鍛鍊物件導向的思維模式
code:
1"""2
this module is used to spider data!
3"""45
from urllib import
request
6importre7
#代替print的斷點除錯方法,特別重要!!!89
10class
spider:
11"""
12this class is used to spider data!
13"""
14 url = '
'15 root_pattern = '
([\s\s]*?)'#
非貪婪模式
16 name_pattern = '
([\s\s]*?)
'17 number_pattern = '
([\s\s]*?)'18
19def
__fetch_content
(self):
20"""
21this class is used to spider data!
22"""
2324 r = request.urlopen(self.url) #
提取到html
25 html_s =r.read()
26 html = str(html_s, encoding='
utf-8')
2728
return
html
2930
def__analysis
(self, html):
31 root_html = re.findall(self.root_pattern, html) #
list32#
print(root_html[0]) # 第一次匹配的結果
3334 anchors =
35for html in
root_html:
36 name =re.findall(self.name_pattern, html)
37 number =re.findall(self.number_pattern, html)
38 anchor =
3940
#print(anchors[0])
4142
return
anchors
4344
@staticmethod
45def
__refine
(anchors):
46 i = lambda anchor:
49return
map(i, anchors)
5051
def__sort(self, anchors): #
業務處理
52 anchors = sorted(anchors, key=self.__sort_seek, reverse=true)
53return
anchors
5455
@staticmethod
56def
__sort_seek
(anchors):
57 r = re.findall('
\d*', anchors['
number'])
58 number =float(r[0])
59if'萬
'in anchors['
number']:
60 number *= 10000
6162
return
number
6364
@staticmethod
65def
__show
(anchors):66#
for anchor in anchors:67#
print(anchor['name'] + '-----' + anchor['number'])
68for rank in
range(0, len(anchors)):
69print('
rank
' + str(rank + 1)
70 + '
: ' + anchors[rank]['
name']
71 + '
' + anchors[rank]['
number'])
7273
def go(self): #
主方法(平級的函式)
74 html = self.__fetch_content() #
獲取到文字
75 anchors = self.__analysis(html) #
分析資料
76 anchors = self.__refine(anchors) #
精煉資料77#
print(list(anchors))
78 anchor = self.__sort
(anchors)
79 self.__show
(anchor)
8081
82 spider =spider()
83 spider.go()
python爬蟲基礎
一 什麼是爬蟲 通常爬蟲是從某個 的某個頁面開始,爬取這個頁面的內容,找到網頁中的其他鏈結位址,然後從這個位址爬到下乙個頁面,這樣一直不停的爬下去,進去批量的抓取資訊。那麼,我們可以看出網路爬蟲就是乙個不停爬取網頁抓取資訊的程式。二 爬蟲的基本流程 1,發起請求 向目標站點傳送乙個requests請...
python爬蟲基礎
爬蟲 爬蟲,全稱網路爬蟲,指按照一定的規則 模擬瀏覽器人工登入網頁的方式 自動抓取網路資訊資料的程式。簡單的說,就是將瀏覽器上網所能看到頁面上的內容通過爬蟲程式自動獲取下來,並進行儲存。爬蟲其實就是乙個程式自動收集獲取指定網路資料資訊的過程,網路資料資訊量十分龐大,人工獲取無法完成,這時就需要爬蟲來...
python 爬蟲基礎
urllib 或 requests re 01 r 大圖的 pat re.compile re 01 建立乙個正規表示式的模板 imgurls re.findall pat,data 開始匹配 print len imgurls imgurls i 0 for imgurl in imgurls i...