爬蟲主要流程

2021-08-15 14:59:07 字數 3152 閱讀 2474

'第一種方法'

response1 = urllib2.urlopen(url)

print response1.getcode() #請求狀態碼

print len(response1.read()) #read爬取網頁資訊

print

'第二種方法,新增頭部資訊,模擬瀏覽器訪問'

request = urllib2.request(url) #生成乙個請求物件

request.add_header('user-agent','mozilla/5.0') #在請求物件裡新增請求頭部資訊

response2 = urllib2.urlopen(request)

print response2.getcode() #請求狀態碼

print len(response2.read()) #read爬取網頁資訊

print

'第三種方法,有的瀏覽器需要登入,需新增cookie處理功能'

cj = cookielib.cookiejar() #建立乙個cookie容器物件

opener = urllib2.build_opener(urllib2.httpcookieprocessor(cj)) #建立乙個具有httpcookieprocessor方法的opener物件

urllib2.install_opener(opener) #給urllib2安裝這個opener,urllib2就有了cookie處理的能力

response3 = urllib2.urlopen(url)

print response3.getcode() #請求狀態碼

print response3.read() #read爬取網頁資訊

para" label-module="para">在電腦科學中" class="sister" id="link1">elsie,

" class="sister" id="link2">lacie and

" class="sister" id="link3">tillie;

and they lived at the bottom of a well.

story">..."""

#建立解析html的soup物件

soup = beautifulsoup( html_doc, #html文件

'html.parser', #html直譯器

from_encoding='utf-8'

#html文件使用的編碼

)# 搜尋節點標籤方法 find_all/find(name,attrs,string)

#node = soup.find_all('a',class_='abc',string='python') #class加下劃線是為了區別關鍵字

#node.name #獲取你標籤名字

#name['href']#以字典的形式訪問href屬性的值

#node.get_text()#獲取節點中的鏈結文字

print

'獲取所有鏈結'

node = soup.find_all('a')

print

'node',node

forlink in node:

print

link.name, link['href'], link.get_text()

print

'獲取指定url鏈結'

node_link = soup.find('a', class_='sister')

print node_link.name, node_link['href'], node_link.get_text()

print

'使用正則表達進行模糊匹配'

node = soup.find('div', class_='para').find_all('a', href=re.compile('exa'))

for node_link in node:

print node_link.name, node_link['href'], node_link.get_text()

#1、compile()

#編譯正規表示式模式,返回乙個物件的模式。(可以把那些常用的正規表示式編譯成正規表示式物件,這樣可以提高一點效率。)

#格式:

#re.compile(pattern,flags=0)

#pattern: 編譯時用的表示式字串。

#flags 編譯標誌位,用於修改正規表示式的匹配方式,如:是否區分大小寫,多行匹配等。常用的

爬蟲學習 爬蟲基本流程

標籤 空格分隔 資料探勘 爬蟲 1 發起請求 2 獲取相應內容 3 解析網路內容 4 儲存資料 結構化儲存 user server request server user response 1 請求方式 get,post,head,put,delete 2 get和post的區別 請求的引數包含的部...

爬蟲資料之爬蟲流程

多頁面爬蟲流程 有的網頁存在多頁的情況,每頁的網頁結構都相同或類似,這種型別的網頁爬蟲流 程為 手動翻頁並觀察各網頁的url 構成特點,構造出所有頁面的url 存入列表中。根據url 列表依次迴圈取出url 定義爬蟲函式。迴圈呼叫爬蟲函式,儲存資料。迴圈完畢,結束爬蟲程式 跨頁面爬蟲流程 定義爬取函...

Cakephp 執行主要流程

載入基本檔案 cake basics.php 裡面定義了常用的方法以及時間常量 time start getmicrotime 記錄開始執行時間 cake config paths.php 裡面定義一些基本路徑 cake lib object.php cake的基本類 cake lib inflec...