上一篇,我們使用了python自帶的urllib和re庫完成了爬蟲的入門案例,點擊進入博客
但是,由于正則表達式難以掌握,我們用一個第三方庫:BeautifulSoup,來對網頁內容進行截取
一,下載并安裝BeautifulSoup
如果python3.x安裝了pip3,就可以使用pip3命令行來安裝BeautifulSoup
pip3 install beautifulsoup4如果沒有安裝pip3,也可以通過源碼安裝下載源碼包(點擊下載),進入到包目錄下通過命令行安裝
python setup.py install安裝好后,進入python,測試是否安裝成功
from bs4 import BeautifulSoup沒有報錯就是安裝成功了。bs4的中文文檔請參見頁面:http://beautifulsoup.readthedocs.io/zh_CN/latest/
二,使用
先看一下bs的基本使用方法
import urllib.requestfrom bs4 import BeautifulSoupdef getHtmlCode(url): # 該方法傳入url,返回url對應的html的源碼 headers = { 'User-Agent': 'Mozilla/5.0 (linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36' } url1 = urllib.request.Request(url, headers=headers) # Request函數將url添加頭部,模擬瀏覽器訪問 page = urllib.request.urlopen(url1).read() # 將url頁面的源代碼保存成字符串 page = page.decode('UTF-8') # 字符串轉碼 return pageif __name__ == '__main__': html = getHtmlCode('http://www.zhangzishi.cc/20160413hx.html') soup = BeautifulSoup(html,"html.parser") # BeautifulSoup類解析url源碼并返回一個對象 PRint(type(soup)) print(soup.prettify()) # 按照標準的縮進格式的結構輸出 print(soup.p) # 輸出源碼中第一個p標簽 print(soup.p.name) # 輸出標簽的名字p print(soup.title.string) # 輸出標簽的內容 # 獲得標簽屬性內容的第一種方法 print(soup.a['href']) # 獲得標簽屬性內容的第二種方法 img = soup.img print(img.get('src')) # find_all找到所有的img標簽,并返回一個列表 print(soup.find_all('img')) # 結合上兩步,獲得所有img標簽中的src屬性內容 imgList = soup.find_all('img') for i in imgList: print(i.get('src')) print(type(i.get('src'))) # get返回的是字符串三,結合urllib和bs4來完成爬蟲程序import urllib.requestfrom bs4 import BeautifulSoupdef getHtmlCode(url): # 該方法傳入url,返回url的html的源碼 headers = { 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36' } url1 = urllib.request.Request(url, headers=headers) # Request函數將url添加頭部,模擬瀏覽器訪問 page = urllib.request.urlopen(url1).read() # 將url頁面的源代碼保存成字符串 page = page.decode('UTF-8') # 字符串轉碼 return pagedef getImg(page,localPath): # 該方法傳入html的源碼,經過截取其中的img標簽,將圖片保存到本機 soup = BeautifulSoup(page,'html.parser') # 按照html格式解析頁面 imgList = soup.find_all('img') # 返回包含所有img標簽的列表 x = 0 for imgUrl in imgList: # 列表循環 print('正在下載:%s'%imgUrl.get('src')) # urlretrieve(url,local)方法根據圖片的url將圖片保存到本機 urllib.request.urlretrieve(imgUrl.get('src'),localPath+'%d.jpg'%x) x+=1if __name__ == '__main__': url = 'http://www.zhangzishi.cc/20160928gx.html' localPath = 'e:/pythonSpiderFile/img3/' page = getHtmlCode(url) getImg(page,localPath)
新聞熱點
疑難解答