Python爬取数据并搭建专属API(1)

APP开发社 第六次活动笔记与任务清单

活动主题:PYTHON爬虫搭建与SQL数据库使用

目标:学习python爬虫并了解API(application program interface)的搭建,为我们之后的Android网络应用准备基础

具体流程如下:

1、获取专属api数据(此处需要用到爬虫) —————-30min(今天的部分)

2、搭建api所需的数据库(此处用到sql)——————-30min

CHAPTER 12 Networked programs 网络程序

核心介绍: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.

我们将会先搭建一个游览器,通过python中内置的库来获取网页内容(通过HTTP(HyperText 富文本)协议,然后像访问文件的方式来访问网页中的内容。我们同样也会学习到如何爬取网页上的数据(比如百度百科上的词条介绍)。

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语言中,我们使用内建的socket工具去实现HTTP协议

A socket is much like a file, except that a single socket provides a two-way connection between two programs.

socket工具更像一个文件,而并不是一个程序。

A protocal is a set of precise rules that determine who is to go first.

一个协议就是谁先做什么事情。

例子: 如果我们不遵守协议(protocal) 就会出现网站服务器提供了一个数据,但是客户端(我们的电脑)却没有接收这种尴尬的情况

12.2 The world’s Simplest Web Broswer(务必理解原理)

世界上最简单的游览器(遵循HTTP协议的方式)

// Making for our app developer club

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

//First the program used HTTP protocal

这一行代码意味创建了SOCKEt文件

mysock.connect((‘data.pr4e.org’, 80))

//The program makes a connection to port 80 on the serve www.py4e.com

将这个文件与www.py4e.com 80端口进行连接

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()

我们通过手动创建socket文件,并发送到服务器,然后接收文件,注意到我们最多能一次接受512字节的文件,所以我们需要通过循环来接受,并打印到屏幕上。

12.4 Retrieving web pages with urllib(请将这段程序自己写一段,因为比较实用)

使用urlib访问网页

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是一个python内置库,我们可以使用它免除自己手写HTTP协议的原理(但是明白原理还是很关键的)

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())

其实decode()只是删除了一些空格,大家删除decode()后可以试一下

具体解释,我们通过这个urlopen的函数可以直接获取到文件的一个“快捷方式”,然后像操作文件一样即可。

12.7 Parsing HTML using BeautifulSoup

首先我们先要调用这个库(由于是第三方库,需要自己下载)

链接为: www.crummy.com/software/

    原文作者:Gene2018
    原文地址: https://www.jianshu.com/p/540df5cbeb1a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞