python3.4學(xué)習(xí)筆記(十七) 網(wǎng)絡(luò)爬蟲使用Beautifulsoup4抓取內(nèi)容
Beautiful Soup 是用Python寫的一個(gè)HTML/XML的解析器,它可以很好的處理不規(guī)范標(biāo)記并生成剖析樹(parse tree)。 它提供簡(jiǎn)單又常用的導(dǎo)航(navigating),搜索以及修改剖析樹的操作。它可以大大節(jié)省你的編程時(shí)間。
Beautiful Soup Documentation — Beautiful Soup 4.4.0 documentation
http://www.crummy.com/software/BeautifulSoup/bs4/doc/
[學(xué)習(xí)]用python的BeautifulSoup分析html - 三夜燈 - 博客園
http://www.cnblogs.com/twinsclover/archive/2012/04/26/2471704.html
Beautiful3 Soup documentation 中文文檔只有bs3的,最新的只有英文版的
http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#Quick%20Start
熱血狂徒 / zyspider - 代碼托管 - 開源中國(guó)社區(qū)
http://git.oschina.net/coos/zyspider
python3.4學(xué)習(xí)筆記(十三) 網(wǎng)絡(luò)爬蟲實(shí)例代碼,使用pyspider抓取多牛投資吧里面的文章信息,抓取政府網(wǎng)新聞內(nèi)容 - 流風(fēng),飄然的風(fēng) - 博客園
http://www.cnblogs.com/zdz8207/p/python_learn_note_13.html
============================================
BeautifulSoup4的安裝
一、使用pip直接安裝beautifulsoup4 (如何安裝pip請(qǐng)看上一篇文章介紹)
F:\kanbox\pythoncode\zyspider>pip install beautifulsoup4
Collecting beautifulsoup4
Downloading beautifulsoup4-4.4.0-py3-none-any.whl (80kB)
328kB/s
Installing collected packages: beautifulsoup4
Successfully installed beautifulsoup4-4.4.0
F:\kanbox\pythoncode\zyspider>
或者從官網(wǎng)下載Beautifulsoup的軟件包,然后解壓,cmd命令行進(jìn)入解壓包目錄,輸入以下命令安裝:python setup.py install
=======================================
網(wǎng)絡(luò)爬蟲實(shí)例代碼,抓取新浪愛彩雙色球開獎(jiǎng)數(shù)據(jù)實(shí)例代碼:
1 __author__ = 'zdz8207' 2 from bs4 import BeautifulSoup 3 4 import urllib.request 5 import urllib.parse 6 import re 7 import urllib.request, urllib.parse, http.cookiejar 8 9 def getHtml(url):10 cj = http.cookiejar.CookieJar()11 opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))12 opener.addheaders = [('User-Agent',13 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36'),14 ('Cookie', '4564564564564564565646540')]15 16 urllib.request.install_opener(opener)17 18 html_bytes = urllib.request.urlopen(url).read()19 html_string = html_bytes.decode('utf-8')20 return html_string21 22 html_doc = getHtml("http://zst.aicai.com/ssq/openInfo/")23 soup = BeautifulSoup(html_doc, 'html.parser')24 25 # print(soup.title)26 #table = soup.find_all('table', class_='fzTab')27 #print(table)#<tr onmouseout="this.style.background=''" 這種tr丟失了28 #soup.strip() 加了strip后經(jīng)常出現(xiàn)find_all('tr') 只返回第一個(gè)tr
29 tr = soup.find('tr',attrs={"onmouseout": "this.style.background=''"}) 30 #print(tr) 31 tds = tr.find_all('td') 32 opennum = tds[0].get_text() 33 #print(opennum) 34 35 reds = [] 36 for i in range(2,8): 37 reds.append(tds[i].get_text()) 38 #print(reds) 39 blue = tds[8].get_text() 40 #print(blue) 41 42 #把list轉(zhuǎn)換為字符串:(',').join(list) 43 #最終輸出結(jié)果格式如:2015075期開獎(jiǎng)號(hào)碼:6,11,13,19,21,32, 藍(lán)球:4 44 print(opennum+'期開獎(jiǎng)號(hào)碼:'+ (',').join(reds)+", 藍(lán)球:"+blue)
python3.4學(xué)習(xí)筆記(十四) 網(wǎng)絡(luò)爬蟲實(shí)例代碼,抓取新浪愛彩雙色球開獎(jiǎng)數(shù)據(jù)實(shí)例 - 流風(fēng),飄然的風(fēng) - 博客園
http://www.cnblogs.com/zdz8207/p/python_learn_note_14.html
從上實(shí)例可以看出使用BeautifulSoup4對(duì)比直接使用字符串查找截取的方式要更加直觀和簡(jiǎn)潔。
=======================================
Python2.7 安裝 beautifulsoup4-4.4.0 下載地址:http://www.crummy.com/software/BeautifulSoup/bs4/download/4.4/
安裝方法:cmd, cd進(jìn)入beautifulsoup的 setup.py 所在的那個(gè)目錄(如: D:\download\beautifulsoup4-4.4.0),然后運(yùn)行
python setup.py build
python setup.py install
版本升級(jí)到4,引入包要用
import bs4
from bs4 import BeautifulSoup
不能直接用
from BeautifulSoup import BeautifulSoup
python3.4中可以直接使用from bs4 import BeautifulSoup
注:在同一臺(tái)電腦上安裝2.7和3.4的會(huì)導(dǎo)致使用pip命令在2.7情況下安裝不了Beautifulsoup4
=======================================
導(dǎo)入模塊
#!/usr/bin/env python
from bs4 import BeautifulSoup #process html
#from bs4 import BeautifulStoneSoup #process xml
#import BeautifulSoup #all
創(chuàng)建對(duì)象:str初始化,常用urllib2或browser返回的html初始化BeautifulSoup對(duì)象。
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 class="sister" id="link1">Elsie</a>
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc)
soup 就是BeautifulSoup處理格式化后的字符串,soup.title 得到的是title標(biāo)簽,soup.p 得到的是文檔中的第一個(gè)p標(biāo)簽,要想得到所有標(biāo)簽,得用find_all
函數(shù)。find_all 函數(shù)返回的是一個(gè)序列,可以對(duì)它進(jìn)行循環(huán),依次得到想到的東西.
get_text() 是返回文本,這個(gè)對(duì)每一個(gè)BeautifulSoup處理后的對(duì)象得到的標(biāo)簽都是生效的。你可以試試 print soup.p.get_text()
其實(shí)是可以獲得標(biāo)簽的其他屬性的,比如我要獲得a標(biāo)簽的href屬性的值,可以使用 print soup.a['href'],類似的其他屬性,比如class也是可以這么得到的(soup.a['class'])。
特別的,一些特殊的標(biāo)簽,比如head標(biāo)簽,是可以通過(guò)soup.head 得到,其實(shí)前面也已經(jīng)說(shuō)了。
如何獲得標(biāo)簽的內(nèi)容數(shù)組?使用contents 屬性就可以 比如使用 print soup.head.contents,就獲得了head下的所有子孩子,以列表的形式返回結(jié)果,
可以使用 [num] 的形式獲得 ,獲得標(biāo)簽,使用.name 就可以。
獲取標(biāo)簽的孩子,也可以使用children,但是不能print soup.head.children 沒有返回列表,返回的是 <listiterator object at 0x108e6d150>,
不過(guò)使用list可以將其轉(zhuǎn)化為列表。當(dāng)然可以使用for 語(yǔ)句遍歷里面的孩子。
關(guān)于string屬性,如果超過(guò)一個(gè)標(biāo)簽的話,那么就會(huì)返回None,否則就返回具體的字符串print soup.title.string 就返回了 The Dormouse's story
超過(guò)一個(gè)標(biāo)簽的話,可以試用strings
向上查找可以用parent函數(shù),如果查找所有的,那么可以使用parents函數(shù)
查找下一個(gè)兄弟使用next_sibling,查找上一個(gè)兄弟節(jié)點(diǎn)使用previous_sibling,如果是查找所有的,那么在對(duì)應(yīng)的函數(shù)后面加s就可以
如何遍歷樹?
使用find_all 函數(shù)
find_all(name, attrs, recursive, text, limit, **kwargs)
舉例說(shuō)明:
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" id="link1">Elsie</a>, <a class="sister" id="link2">Lacie</a>, <a class="sister" id="link3">Tillie</a>]
[<a class="sister" id="link2">Lacie</a>]
[<a class="sister" id="link1">Elsie</a>, <a class="sister" id="link2">Lacie</a>, <a class="sister" id="link3">Tillie</a>]
通過(guò)css查找,直接上例子把:
print soup.find_all("a", class_="sister")
print soup.select("p.title")
通過(guò)屬性進(jìn)行查找
print soup.find_all("a", attrs={"class": "sister"})
通過(guò)文本進(jìn)行查找
print soup.find_all(text="Elsie")
print soup.find_all(text=["Tillie", "Elsie", "Lacie"])
限制結(jié)果個(gè)數(shù)
print soup.find_all("a", limit=2)
結(jié)果為:
[<a class="sister" id="link1">Elsie</a>, <a class="sister" id="link2">Lacie</a>, <a class="sister" id="link3">Tillie</a>]
[<p class="title"><b>The Dormouse's story</b></p>]
[<a class="sister" id="link1">Elsie</a>, <a class="sister" id="link2">Lacie</a>, <a class="sister" id="link3">Tillie</a>]
[u'Elsie']
[u'Elsie', u'Lacie', u'Tillie']
[<a class="sister" id="link1">Elsie</a>, <a class="sister" id="link2">Lacie</a>]
總之,通過(guò)這些函數(shù)可以查找到想要的東西。
=================================================
最簡(jiǎn)單的爬蟲,在Python3中,urllib庫(kù)可以獨(dú)立完成這些工作。下面是直接在python控制臺(tái)上輸入的代碼最簡(jiǎn)單的爬蟲,可以獲取到原始字節(jié)及解碼后的文本。
>>> 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現(xiàn)在得到了傳輸過(guò)來(lái)的原始字節(jié),而origin_string則是將這些原始字節(jié)以UTF-8編碼方式解碼出來(lái)的原始字符串。
然后我們就可以使用各種HTML解析工具或單純地用文本解析工具來(lái)獲取需要的數(shù)據(jù)。
使用headers偽裝成瀏覽器進(jìn)行訪問(wèn)
有的網(wǎng)站比如說(shuō)http://www.oschina.net,如果用上面那種方法來(lái)訪問(wèn),則會(huì)返回403拒絕訪問(wèn)的錯(cuò)誤信息。這是因?yàn)橛胁糠志W(wǎng)站禁止除瀏覽器之外的方法進(jìn)行訪問(wèn)。
需要在發(fā)送請(qǐng)求的時(shí)候加入headers信息,偽裝成瀏覽器,這樣就不會(huì)出現(xiàn)403的錯(cuò)誤了。抓取頻繁時(shí)還需要變化head信息和采用代理IP的方式。
下面是一個(gè)最簡(jiǎn)單的使用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可以從瀏覽器的調(diào)試工具中看到,比如firefox中的firebug,可以復(fù)制curl內(nèi)容進(jìn)行分析。
聯(lián)系客服