小白自学Python3爬虫

来源:互联网 发布:2016网络最热门话题 编辑:程序博客网 时间:2024/05/16 23:32

2017.10.30

使用语言:Python3

使用IDE:pycharm


第一段程序:爬http.www.baidu.com页面

#导入uellib.request库,它是隶属于urllib的一个库,其主要功能是:#打开URL,大多数是httpimport urllib.requesturl="http://www.baidu.com"data=urllib.request.urlopen(url)#返回http.client.HTTPResponsedata=data.read()data=data.decode('Utf-8')print(data)
用Python处理简单的URL
#抓取百度上面搜索关键词为Jecvay Notes的网页import urllibimport  urllib.requestdata={ }#data是一个字典data['word']='Jecvay Notes'#urlencode()把一个通俗的字符串, 转化为url格式的字符串url_values=urllib.parse.urlencode(data)#urllib.parse.urlencode()来将data转换为 ‘word=Jecvay+Notes’的字符串url="htttp://www.baidu.com/s?"full_url=url+url_valuesdata=urllib.request.urlopen(full_url)data=data.read()data=data.decode('UTF-8')print(data)

因为Python中list效率比较低,所以用collection.queue
官方介绍collection.queue使用
2
3
4
5
6
7
8
9
10
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry 入队
queue.append("Graham")          # Graham 入队
queue.popleft()                 # 队首元素出队
#输出: 'Eric'
queue.popleft()                 # 队首元素出队
#输出: 'John'
queue                           # 队列中剩下的元素
#输出: deque(['Michael', 'Terry', 'Graham'])
在爬虫过程中为了不重复爬已经爬过的URL,我们将爬过的URL放到一个集合当中。

Python中set提供了这种数据要求,set是一种具有无序、互异性的集合。

创建一个set可以使用set()或者{},但是空集合不能使用{},空的{}表示字典数据




2
3
4
5
6
7
8
9
10
fromcollectionsimportdeque
queue=deque(["Eric","John","Michael"])
queue.append("Terry")          # Terry 入队
queue.append("Graham")          # Graham 入队
queue.popleft()                # 队首元素出队
#输出: 'Eric'
queue.popleft()                # 队首元素出队
#输出: 'John'
queue                          # 队列中剩下的元素
#输出: deque(['Michael', 'Terry', 'Graham'])
原创粉丝点击