python 爬蟲(一) requests+BeautifulSoup 爬取簡單網頁程式碼範例

來源:互聯網
上載者:User

標籤:parser   beautiful   顏色   div   爬取   sts   auth   ...   傳參   

以前搞偷偷摸摸的事,不對,是搞爬蟲都是用urllib,不過真的是很麻煩,下面就使用requests + BeautifulSoup 爬爬簡單的網頁。

詳細介紹都在代碼中注釋了,大家可以參閱。

# -*- coding: utf-8 -*-"""Created on Thu Jul  5 20:48:25 2018@author: brave-manblog: http://www.cnblogs.com/zrmw/python3 + anaconda(Spyder) + resquests + BeautifulSoup這裡環境用的就是昨天講的 anaconda 下的 Spyder,非常方便,誰用誰知道"""import requestsfrom bs4 import BeautifulSoup# from termcolor import colored# 控制台輸出文本顏色控制,網路不太好,沒有安裝termcolor,不過在公司測試過,函數傳參應該沒有問題# print("abc", "red")# 通過requests庫中的get方法擷取整個響應頁面,存放在res中res = requests.get("https://www.cnblogs.com/zdong0103/p/8492779.html")# (1) res.encoding = "utf-8"soup = BeautifulSoup(res.text, "html.parser")# 這時候如果列印的soup的話,會在控制台中輸出整個響應頁面的原始碼# print(soup)# 如果列印的是亂碼,則可以在 (1) 處添加 (1) 所示代碼,設定編碼格式,不過有時候是不需要的。# 接下來對網頁的源碼進行剖析""" 在網頁中按 F12 查看網頁原始碼,文章標題在 class = "block_title" 裡面,soup.select(".block_title") 擷取的是一個列表,擷取此列表的第一個元素,所以 index = 0 , 從標籤中擷取文本一般使用 text 方法即可同上,本文在 class = "blogpost-body"..."""title = soup.select(".block_title")[0].texttexts = soup.select(".blogpost-body")[0].texttime = soup.select(".itemdesc span")[0].textauthor = soup.select("#header")[0].textprint(title, author, time, texts)

發現自己表述能力真的是渣啊,慢慢提高吧。

python 爬蟲(一) requests+BeautifulSoup 爬取簡單網頁程式碼範例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.