APP開發(fā)社 第六次活動筆記與任務(wù)清單
活動主題:PYTHON爬蟲搭建與SQL數(shù)據(jù)庫使用
目標(biāo):學(xué)習(xí)python爬蟲并了解API(application program interface)的搭建胶征,為我們之后的Android網(wǎng)絡(luò)應(yīng)用準(zhǔn)備基礎(chǔ)
具體流程如下:
1续挟、獲取專屬api數(shù)據(jù)(此處需要用到爬蟲) ----------------30min(今天的部分)
2侥祭、搭建api所需的數(shù)據(jù)庫(此處用到sql)-------------------30min
CHAPTER 12 Networked programs 網(wǎng)絡(luò)程序
核心介紹:In this chapter, we will pretend to be a web browser and retrieve(獲群伞)web pages using the HyperText Transfer Protocol(HTTP). Then we will read through the web page data and parse it.
我們將會先搭建一個(gè)游覽器,通過python中內(nèi)置的庫來獲取網(wǎng)頁內(nèi)容(通過HTTP(HyperText 富文本)協(xié)議,然后像訪問文件的方式來訪問網(wǎng)頁中的內(nèi)容找筝。我們同樣也會學(xué)習(xí)到如何爬取網(wǎng)頁上的數(shù)據(jù)(比如百度百科上的詞條介紹)禽篱。
12.1 HTTP Protocal
The network protocol that powers the web is actually quite simple and there is built-in support in Python called sockets.
在python語言中,我們使用內(nèi)建的socket工具去實(shí)現(xiàn)HTTP協(xié)議
A socket is much like a file, except that a single socket provides a two-way connection between two programs.
socket工具更像一個(gè)文件丈咐,而并不是一個(gè)程序瑞眼。
A protocal is a set of precise rules that determine who is to go first.
一個(gè)協(xié)議就是誰先做什么事情。
例子: 如果我們不遵守協(xié)議(protocal) 就會出現(xiàn)網(wǎng)站服務(wù)器提供了一個(gè)數(shù)據(jù)扯罐,但是客戶端(我們的電腦)卻沒有接收這種尷尬的情況
12.2 The world's Simplest Web Broswer(務(wù)必理解原理)
世界上最簡單的游覽器(遵循HTTP協(xié)議的方式)
// Making for our app developer club
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
//First the program used HTTP protocal
這一行代碼意味創(chuàng)建了SOCKEt文件
mysock.connect(('data.pr4e.org', 80))
//The program makes a connection to port 80 on the serve www.py4e.com
將這個(gè)文件與www.py4e.com 80端口進(jìn)行連接
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
? ? data = mysock.recv(512)
? ? if len(data) < 1:
? ? ? ? break
? ? print(data.decode(),end='')
mysock.close()
我們通過手動創(chuàng)建socket文件负拟,并發(fā)送到服務(wù)器,然后接收文件歹河,注意到我們最多能一次接受512字節(jié)的文件掩浙,所以我們需要通過循環(huán)來接受,并打印到屏幕上秸歧。
12.4 Retrieving web pages with urllib(請將這段程序自己寫一段厨姚,因?yàn)楸容^實(shí)用)
使用urlib訪問網(wǎng)頁
While we can manually send and receive data over HTTP using the socket library tere is a much simpler way to perform this common task in Python by using the urllib.
注釋:urlib是一個(gè)python內(nèi)置庫,我們可以使用它免除自己手寫HTTP協(xié)議的原理(但是明白原理還是很關(guān)鍵的)
The code will be much shorter
代碼長度會非常友好
具體代碼如下
import urllib.request
fhand = urllib.request.urlopen("http://data.pr4e.org/romeo.txt")
for line in fhand:
? ? print(line.decode())
其實(shí)decode()只是刪除了一些空格键菱,大家刪除decode()后可以試一下
具體解釋谬墙,我們通過這個(gè)urlopen的函數(shù)可以直接獲取到文件的一個(gè)“快捷方式”,然后像操作文件一樣即可经备。
12.7 Parsing HTML using BeautifulSoup
首先我們先要調(diào)用這個(gè)庫(由于是第三方庫拭抬,需要自己下載)
鏈接為: www.crummy.com/software/