被爬蟲的網址是http://www.heibanke.com/lesson/crawler_ex00/需要完成的任務是在網址后面輸入顯示的數字轉入下一個網址,再次讀取顯示的數字,轉入下一個網址,以此循環
爬蟲要求
在爬蟲的時候需要需要用到兩個庫,一個urllib,一個BeautifulSoup,urllib為python自帶的庫,beautifulsoup需要自己安裝
pip install beautifulsoup4
安裝成功后導入
import urllibfrom bs4 import BeautifulSoup
urllib提供了一系列用于操作URL的功能打開要爬取得網站:
urllib.urlopen(url)
beautifulsoup主要用于解析HTML,將 HTML轉化成數型結構,每個節點都是Python對象。所有對象可以歸納為4種:1.Tag2.NavigableString3.BeautifulSoup4.Comment如果一個HTML為
<[head])>The Dormouse's story
print soup.title>>>The Dormouse's story
print soup.title.string>>>The Dormouse's story
程序邏輯:讀出頁面上的數字,將數字加在url后面,繼續讀取新頁面的數字,直到進入最后一個沒有數字的頁面,break程序如下:
import urllibfrom bs4 import BeautifulSoupimport re#這個庫導入是為了使用正則表達式讀取讀取找到的內容中的數字url='http://www.heibanke.com/lesson/crawler_ex00/'number=['']#用于儲存讀到的數字while True: content = urllib.urlopen(url+number[0])#number為字符串,number[0]為數字 bs_obj = BeautifulSoup(content,"html.parser")#html.parser表示解析網站,不返回任何值 number = bs_obj.h3.string#網頁顯示出的“你需要在網址后輸入數字44513”在html的h3 tag中,number在這里讀出了h3里面的內容 number= re.findall(r'\d+',number)#讀出了number里面的數字 if not number:#必須判斷頁面中還有是否還有number,沒有說明已經到了最后一個頁面,這時應該跳出循環,打印 bs_obj.h3.string break else: print number[0]print bs_obj.h3.string
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com