python簡易爬蟲實現

來源:互聯網
上載者:User

標籤:nic   介紹   amp   return   解壓   多少   url   out   簡單   

目的:爬取暱稱

目標網站:糗事百科

依賴的庫檔案:request、sys、beautifulSoup4、imp、io

Python使用版本:3.4

說明:參考http://cn.python-requests.org/zh_CN/latest/user/quickstart.html

步驟:

一、熟悉request

Request介紹:

  Request庫是一個python http庫,其內部依賴urllib3庫。

  以下是它的功能特性:
  國際化網域名稱和 URL、Keep-Alive & 串連池、帶持久 Cookie 的會話、瀏覽器式的 SSL 認證、基本/摘要式的身份認證、優雅的 key/value Cookie、自動解壓、自動內容解碼、Unicode 響應體、檔案分塊上傳、連線逾時、流下載、支援 .netrc、分塊請求、安全執行緒。

Request API操作:

  Request的API對所有HTTP請求類型都是顯而易見的,例如對於HTTP的請求類型:

  GET、POST、PUT、DELETE、HEAD和OPTIONSS

  對應的request API操作為(例):

       r = requests.get(‘https://github.com/timeline.json‘)

  r = requests.post("http://httpbin.org/post")

  r = requests.put("http://httpbin.org/put")

   r = requests.delete("http://httpbin.org/delete")

   r = requests.head("http://httpbin.org/get")

   r = requests.options("http://httpbin.org/get")

本文主要針對request的擷取操作來做說明:

以GitHubHub時間軸和伺服器響應的內容格式為例:

1、響應內容

import requests

r = requests.get(‘https://github.com/timeline.json‘)

r.text

  Requests可以根據伺服器響應的內容自動解碼,支援大多數unicode,當然我們也可以以指定的解碼格式來解碼內容,如r.text前加上r.encoding = ‘utf-8‘.

2、二進位響應內容和json響應內容

r.content

r.json()

調用該兩種方法分別替換上文的r.text,則分別表示位元組的方式訪問請求的內容,而非文字格式設定和以json的格式解碼內容。

3、原始響應內容

 import requests

r = requests.get(‘https://github.com/timeline.json‘,stream=True)

r.raw

r.raw.read(10)

#將擷取的未經處理資料寫入test.txt檔案

with open(‘test.txt‘,‘wb‘) as fd:

for chunk in r.iter_content(10):

fd.write(chunk)

二、beautifulSoup介紹:

  這是Python的一個庫,在此主要的作用是從爬取到的網頁內容中擷取資料,Beautiful Soup提供一些簡單的、python式的函數用來處理導航、搜尋、修改分析樹等功能。它是一個工具箱,通過解析文檔為使用者提供需要抓取的資料,因為簡單,所以不需要多少代碼就可以寫出一個完整的應用程式。

三、爬取暱稱

  由於本人初次使用Python,所以就做一個最簡單的爬蟲吧!代碼非常簡單,就只是擷取糗事百科的首頁的暱稱:

 

 1 # -*- coding: UTF-8 -*- 2 from bs4 import BeautifulSoup 3 from imp import reload 4 import requests 5 import sys 6 import io 7 sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding=‘utf8‘) 8 #解決unicode編碼與ascll編碼不相容的問題 9 #reload(sys)10 #sys.setdefaultencoding("utf-8")11 ############################12 class Crawler(object):13    def __init__(self):14             print("開始爬取資料")15 #getSource擷取網頁原始碼16    def getSource(self,url):17        html = requests.get(url)18        #print(str(html.text))可以在此列印,看是否抓取到內容19        return html.text20                            21 22 23 #主函數24 if __name__==‘__main__‘:25    url = ‘http://www.qiushibaike.com‘26    testCrawler = Crawler()27    content = testCrawler.getSource(url)28    soup = BeautifulSoup(content)29    fd = open("crawler.txt", ‘w‘) 30    for i in soup.find_all(‘h2‘):31                 print(i.getText())32                 fd.write(i.getText()+‘\n‘)33    fd.close()

 

 

  

 

 

 

 

 

python簡易爬蟲實現

聯繫我們

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