爬蟲學習,第一節課 Your First Web Scraper
說明
學習筆記,用的例子都是書上或者改了幾個字元的0 0
版本和依賴包
Python 3.52
標準包 urllib
依賴包 BeautifulSoup
包管理工具 pip(全地球人都在使用的)
urllib.request中urlopen的使用
urllib是python標準包裡面的一個,在python3中被分成了三大模組,無需安裝就可以馬上使用,當然需要import,而這裡只用到其中一個urlopen.request的function。
from urllib.request import urlopen
html = urlopen("www.baidu.com" )
print(html.read())
使用這段程式碼就可以在console裡面打印出百度首頁這個宇宙最強搜尋器的首頁html內容,好像不止html,才剛入門就先不探究了。
BeautifulSoup
可以看到上面得到的html內容異常混亂,蛇鼠一鍋,而python最好的地方在於肯定一個一個包能用在小地方,所以,書上介紹可以用BeautifulSoup來美化。
BeautifulSoup不是一個標準包,需要下載安裝,肯定得懶懶的用pip。
值得注意的是
1.使用pip需要安裝 “beautifulsoup4”,後面是有”4”的
2.import的時候需要引入的是”BS4”
使用BeautifulSoup寫法如下:
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.baidu.com")
bsObj = BeautifulSoup(html.read())
print(bsObj.html)
使用console裡面也是一團糟 - -///,但是總算是有了分行。壯我宇宙第一搜索器的強大的前端。
使用bs4生成的bsObj是:
>>> type(bsObj)
<class 'bs4.BeautifulSoup' >
這個物件可以通過是類似於javascript的鏈式呼叫
bsObj.html.body.h1
bsObj.body.h1
bsObj.html.h1
捕獲錯誤
為了防止各種出錯造成的爬蟲爬著爬著就趴了的情況,得啟用try-exceptionde
的組合
通過HTTPError
捕獲請求錯誤,通過AttributeError
捕獲空請求錯誤等。
書上的例子如下。
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def getTitle(url):
try:
html_responce = urlopen(url)
html_bytes = html_responce.read()
html = html_bytes.decode("gbk")
except HTTPError as e:
return None
try:
bsObj = BeautifulSoup(html, "html.parser")
title = bsObj.body.h1
except AttributeError as e:
return None
return title
title = getTitle("http://www.qq.com")
if title == None:
print("Ttile could not be found")
else:
print(title)
問題
原版的程式碼出現了編碼錯誤
通過增加在讀取html的responce 後增加解碼html = html_bytes.decode("gbk")
錯誤得到了解決,顯示出中文
pydev debugger: process 13340 is connecting
Connected to pydev debugger (build 162.1967.10)
<h1>
<a class="qqlogo" href="http://www.qq.com" target="_blank">
<span class="undis">騰訊網</span>
</a>
</h1>
Process finished with exit code 0
編碼問題得到了解決