python 爬蟲隨筆-beautifulsoup使用

1.安裝 pip install BeautifulSoup42.導入模塊   #!/usr/bin/env python   from bs4 import BeautifulSoup #process html   #from bs4 import BeautifulStoneSoup #process xml   #import BeautifulSoup #all   建立對象:str初始化,經常使用urllib2或browser返回的html初始化BeautifulSoup對象。   html_doc = """   <html><head><title>The Dormouse's story</title></head>   <body>   <p class="title"><b>The Dormouse's story</b></p>   <p class="story"><a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>   and they lived at the bottom of a well.</p>   <p class="story">...</p>   """   soup = BeautifulSoup(html_doc)3.使用        soup 就是BeautifulSoup處理格式化後的字符串,            soup.title 獲得的是title標籤,            soup.p 獲得的是文檔中的第一個p標籤,要想獲得全部標籤,得用find_all函數。            find_all 函數返回的是一個序列,能夠對它進行循環,依次獲得想到的東西.                get_text() 是返回文本,這個對每個BeautifulSoup處理後的對象獲得的標籤都是生效的。你能夠試試 print soup.p.get_text()                實際上是能夠得到標籤的其餘屬性的,好比我要得到a標籤的href屬性的值,                可使用 print soup.a['href'],相似的其餘屬性,好比class也是能夠這麼獲得的(soup.a['class'])            特別的,一些特殊的標籤,好比head標籤,是能夠經過soup.head 獲得,其實前面也已經說了。   如何得到標籤的內容數組?使用contents 屬性就能夠 好比使用 print soup.head.contents,      就得到了head下的全部子孩子,以列表的形式返回結果,可使用 [num] 的形式得到 ,得到標籤,使用.name 就能夠。   獲取標籤的孩子,也可使用children,可是不能print soup.head.children 沒有返回列表,返回的是 <listiterator object at 0x108e6d150>,   不過使用list能夠將其轉化爲列表。固然可使用for 語句遍歷裏面的孩子。   關於string屬性,若是超過一個標籤的話,那麼就會返回None,不然就返回具體的字符串print soup.title.string 就返回了 The Dormouse's story   超過一個標籤的話,能夠試用strings   向上查找能夠用parent函數,若是查找全部的,那麼可使用parents函數   查找下一個兄弟使用next_sibling,查找上一個兄弟節點使用previous_sibling,若是是查找全部的,那麼在對應的函數後面加s就能夠      如何遍歷樹?       使用find_all 函數         find_all(name, attrs, recursive, text, limit, **kwargs)         舉例說明:         print soup.find_all('title')         print soup.find_all('p','title')         print soup.find_all('a')         print soup.find_all(id="link2")         print soup.find_all(id=True)         返回值爲:         [<title>The Dormouse's story</title>]         [<p class="title"><b>The Dormouse's story</b></p>]         [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]         [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]         [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]            經過css查找,直接上例子把:            print soup.find_all("a", class_="sister")            print soup.select("p.title")            經過屬性進行查找            print soup.find_all("a", attrs={"class": "sister"})            經過文本進行查找            print soup.find_all(text="Elsie")            print soup.find_all(text=["Tillie", "Elsie", "Lacie"])            限制結果個數            print soup.find_all("a", limit=2)            結果爲:            [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]            [<p class="title"><b>The Dormouse's story</b></p>]            [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]            [u'Elsie']            [u'Elsie', u'Lacie', u'Tillie']            [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]         總之,經過這些函數能夠查找到想要的東西。=================================================   最簡單的爬蟲,在Python3中,urllib庫能夠獨立完成這些工做。下面是直接在python控制檯上輸入的代碼最簡單的爬蟲,能夠獲取到原始字節及解碼後的文本。   >>> import urllib.request as request   >>> url = 'http://www.baidu.com'   >>> origin_bytes = request.urlopen( url ).read()   >>> origin_string = origin_bytes.decode( 'utf-8' )   >>> print(origin_string)其中origin_bytes如今獲得了傳輸過來的原始字節,而origin_string則是將這些原始字節以UTF-8編碼方式解碼出來的原始字符串。而後咱們就可使用各類HTML解析工具或單純地用文本解析工具來獲取須要的數據。   使用headers假裝成瀏覽器進行訪問   有的網站好比說http://www.oschina.net,若是用上面那種方法來訪問,則會返回403拒絕訪問的錯誤信息。這是由於有部分網站禁止除瀏覽器以外的方法進行訪問。   須要在發送請求的時候加入headers信息,假裝成瀏覽器,這樣就不會出現403的錯誤了。抓取頻繁時還須要變化head信息和採用代理IP的方式。   下面是一個最簡單的使用headers的例子。   >>> import urllib.request as request   >>> url = 'http://www.oschina.net'   >>> headers = ('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11')   >>> opener = request.build_opener()   >>> opener.addheaders = [ headers ]   >>> origin_bytes = opener.open( url ).read()   >>> origin_string = origin_bytes.decode( 'utf-8' )   其中headers能夠從瀏覽器的調試工具中看到,好比firefox中的firebug,能夠複製curl內容進行分析。
相關文章
相關標籤/搜索