學習python網路資料擷取筆記-1、2章,python資料擷取
英文不好只能看中文版的。郵電出版社翻譯的真很爛。
以上是吐槽,以下是本文。
書中用的pthon 3.X版本,建議安裝python3.4以上的版本,低版本的沒有內建pip安裝外掛程式會比較麻煩。
:https://www.python.org/downloads/windows/
1.1注意烏鴉處提示,如果用2.x的版本後面寫urllib.request處替換成urllib或者urllib2.
1.2.1 安裝包命令一定不要寫錯 pip install beatifulsoup4
1.2.2 用html.read() 讀取網頁中ccs樣式裡的h1標籤的內容
#! /usr/bin/env python#coding=utf-8from urllib.request import urlopen#3.*版本是這樣的,2.*去掉後面.request,參照1.1烏鴉處提示from bs4 import BeautifulSouphtml = urlopen("http://www.pythonscraping.com/pages/page1.html")bsObj=BeautifulSoup(html.read())print(bsObj.h1.get_text())
1.2.3設定報錯
網頁不存在 except HTTPError as e:
伺服器不存在 if html is None
屬性錯誤: except AttributeError as e:
如何建立函數,返回報錯。
#! /usr/bin/env python#coding=utf-8from urllib2 import urlopenfrom bs4 import BeautifulSoupfrom urllib2 import HTTPErrordef getTitle(url): try: html =urlopen(url) except HTTPError as e: #e為異常對象執行個體 return None try: bsObj=BeautifulSoup(html.read()) title=bsObj.body.h1 except AttributeError as e: return None return titletitle=getTitle("http://www.pythonscraping.com/pages/pageee1.html")#這裡指定一個無法找到的頁面if title == None: print("title could not be found")else: print(title)
2.2根據標籤屬性抽取文字
namelist=bsObj.findAll("span",{"class":"green"}
#這裡需要主要的是findAll中的A必須要大寫。
get_text()是起到刪除標籤作用,可以將其添加print(bsObj.h1.get_text())中,運行刪除h1標籤
View Code
2.2.1 find和findAll的差別,可用limit限制findAll的尋找層數,具體差別出了limit限制完全沒看明白
2.2.2 beautifulsoup的對象
普通對象 bsObj
標籤Tag對象 bsObj.div.h1
NAvigablesString對像 標籤裡面的文字
Comment對象 尋找注釋文字<!--***-->
2.2.3導航樹--子、兄弟、父標籤
子標籤(children)和後代標籤(descendant)
from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen("http://www.pythonscraping.com/pages/page3.html")bsObj=BeautifulSoup(html)#比1.2中省略了.read()for child in bsObj.find("table",{"id":"giftList"}).children: #.children是子物件,.descendants是所有後代 print (child)
兄弟標籤
from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen("http://www.pythonscraping.com/pages/page3.html")bsObj=BeautifulSoup(html)for sibling in bsObj.find("table",{"id":"giftList"}).tr.next_siblings:#.tr提取標題列#.next_siblings提取除標題列外的資料#.previous_siblings提取最後一行外的資料#上面兩個去掉s只返回單個標籤 print (sibling)
父標籤
from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen("http://www.pythonscraping.com/pages/page3.html")bsObj=BeautifulSoup(html)print (bsObj.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text())#翻譯下來就是列印圖片img1.jpg父親的上級兄弟的刪除標籤結果。
2.3Regex。
此處延伸擴充就能單獨一篇這裡不多介紹,站長工具裡面有Regex工具。
2.4Regex和Beautifulsoup
from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen("http://www.pythonscraping.com/pages/page3.html")bsObj=BeautifulSoup(html)import reimages=bsObj.findAll("img",{"src":re.compile("\.\.\/img\/gifts/img.*\.jpg")})for image in images: print(image["src"])
2.5擷取屬性
介紹的太簡單我也看不明白
2.6Lambda運算式
暫時沒有接觸過
2.7採集還有很多其他的之前用urllibe和urllibe2爬過微博