Python 爬蟲實戰(二):使用 requests-html

來源:互聯網
上載者:User

標籤:iss   art   water   bar   python   detail   code   觀察   attrs   

Python 爬蟲實戰(一):使用 requests 和 BeautifulSoup,我們使用了 requests 做網路請求,拿到網頁資料再用 BeautifulSoup 解析,就在前不久,requests 作者 kennethreitz 出了一個新庫 requests-html,Pythonic HTML Parsing for Humans?,它可以用於解析 HTML 文檔的。requests-html 是基於現有的架構 PyQuery、Requests、lxml 等庫進行了二次封裝,更加方便開發人員調用。

安裝

Mac:

pip3 install requests-html

Windows:

pip install requests-html
執行個體

代碼擼多了,讓我們看會妹紙,爬的網站我選的是 http://www.win4000.com/zt/xinggan.html ,開啟網站,觀察到這是個列表,圖片是縮圖,要想儲存圖片到本地,當然需要高清大圖,因此得進入列表詳情,進一步解析,完整代碼如下:

from requests_html import HTMLSessionimport requestsimport timesession = HTMLSession()# 解析圖片列表def get_girl_list():    # 返回一個 response 對象    response = session.get('http://www.win4000.com/zt/xinggan.html')  # 單位秒數    content = response.html.find('div.Left_bar', first=True)    li_list = content.find('li')    for li in li_list:        url = li.find('a', first=True).attrs['href']        get_girl_detail(url)# 解析圖片詳細def get_girl_detail(url):    # 返回一個 response 對象    response = session.get(url)  # 單位秒數    content = response.html.find('div.scroll-img-cont', first=True)    li_list = content.find('li')    for li in li_list:        img_url = li.find('img', first=True).attrs['data-original']        img_url = img_url[0:img_url.find('_')] + '.jpg'        print(img_url + '.jpg')        save_image(img_url)# 保持大圖def save_image(img_url):    img_response = requests.get(img_url)    t = int(round(time.time() * 1000))  # 毫秒級時間戳記    f = open('/Users/wuxiaolong/Desktop/Girl/%d.jpg' % t, 'ab')  # 儲存圖片,多媒體檔案需要參數b(二進位檔案)    f.write(img_response.content)  # 多媒體儲存content    f.close()if __name__ == '__main__':    get_girl_list()

代碼就這麼多,是不是感覺很簡單啊。

說明:

1、requests-html 與 BeautifulSoup 不同,可以直接通過標籤來 find,一般如下:
標籤
標籤.someClass
標籤#someID
標籤[target=_blank]
參數 first 是 True,表示只返回 Element 找到的第一個,更多使用:http://html.python-requests.org/ ;

2、這裡儲存本地路徑 /Users/wuxiaolong/Desktop/Girl/我寫死了,需要讀者改成自己的,如果直接是檔案名稱,儲存路徑將是項目目錄下。

遺留問題

樣本所耙梳站是分頁的,沒有做,可以定時迴圈來爬妹紙哦,有興趣的讀者自己玩下。

參考

requests-html

今天用了一下Requests-HTML庫(Python爬蟲)

公眾號

我的公眾號:吳小龍同學,歡迎交流~

Python 爬蟲實戰(二):使用 requests-html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.