筆記之《用python寫網絡爬蟲》


1 .3 背景調研

robots. txt

 

Robots協議(也稱為爬蟲協議、機器人協議等)的全稱是“網絡爬蟲排除標准”(Robots Exclusion Protocol),網站通過Robots協議告訴搜索引擎哪些頁面可以抓取,哪些頁面不能抓取。

WHOIS

whois是用來查詢域名的IP以及所有者等信息的傳輸協議。簡單說,whois就是一個用來查詢域名是否已經被注冊,以及注冊域名的詳細信息的數據庫(如域名所有人、域名注冊商)。

1.3.1 檢查robots.txt

  crawler英[ˈkrɔ:lə(r)]
  美[ˈkrɔlɚ]
  n.爬行者,爬行動物

1.3.4 識別網站所用技術

檢查網站 構建的技術類型builtwith 模塊

 

>> import builtwith
>> builtwith.parse('http://exaple.webscraping.com') 

1.3.5 尋找網站所有者 

為了找到網站的所有者,我們可以使用WHOIS協議查詢域名的注冊者是誰 

pip install python-whois

1.4 編寫第一個網絡爬蟲

· 爬取網站地圖;
· 遍歷每個網頁的數據庫ID;
· 跟蹤網頁鏈接  

1.4.1 下載網頁 

4xx 錯誤發生在請求存在問題時,而5xx 錯誤則發生在服務端存在問題時。

1 . 重試下載

2. 設置用戶代理 

import urllib2

def download(url,user_agent='wswp',num_retries = 2):
url = 'http://httpstat.us/500'
print 'Downloading',url
headers = {User-agent:user_agent}
request = urllib2.Request(url,headers = headers)

try:
html = urllib2.urlopen(url).read()
except URLError as e:
print 'Downloading error',e.reason
html = None
if num_retries > 0:
if hasattr(e,'code') and 500<=e.code<600:
return download(url,num_retries-1)
return html

if __name__ == '__main__':
download('http://httpstat.us/500',num_retries =2)

注:1.NameError: global name 'User' is not defined

  2.hasattr(object, name)---作用:判斷對象object是否包含名為name的特性

  3.recursively   遞歸的 

1.4.2 網站地圖爬蟲

import urllib2


def crawel_sitemap(url):
sitemap = download(url)
links = re.findall('<loc>(.*?)<./loc>',sitemap)

for link in links:
html = download(link)

if __name__ == '__main__':
crawel_sitemap('http://exale.webscraping.com/sitemap.xl')

注:1. .*?   *? 重復任意次,但盡可能少重復--非貪婪匹配

  2.extact    英[ˈekstrækt]  美[ɪkˈstrækt]

          vt.提取; (費力地) 拔出; 選取; 獲得;

  3.NameError: global name 'download' is not defined

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM