標籤: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簡易爬蟲實現