Python 3 爬虫学习笔记 (一)

这是我自己在学习python 3爬虫时的小笔记,做备忘用,难免会有一些错误和疏漏,望指正~~~
Python 3 爬虫学习笔记 (二)
Python 3 爬虫学习笔记 (三)
Python 3 爬虫学习笔记 (四)
Python 3 爬虫学习笔记 (五)
Python 3 爬虫学习笔记 (六)


〇. python 基础

先放上python 3 的官方文档:https://docs.python.org/3/ (看文档是个好习惯)
关于python 3 基础语法方面的东西,网上有很多,大家可以自行查找.

一. 最简单的爬取程序

爬取百度首页源代码:

#-*-coding:utf-8 -*-

import urllib.request

url = "http://www.baidu.com"
page_info = urllib.request.urlopen(url).read()
page_info = page_info.decode('utf-8')
print(page_info)

来看上面的代码:

  • 对于python 3来说,urllib是一个非常重要的一个模块 ,可以非常方便的模拟浏览器访问互联网,对于python 3 爬虫来说, urllib更是一个必不可少的模块,它可以帮助我们方便地处理URL.
  • urllib.request是urllib的一个子模块,可以打开和处理一些复杂的网址

The urllib.request
module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.

  • urllib.request.urlopen()方法实现了打开url,并返回一个 http.client.HTTPResponse对象,通过http.client.HTTPResponse的read()方法,获得response body,转码最后通过print()打印出来.

urllib.request.urlopen(url, data=None, [timeout, ]***, cafile=None, capath=None, cadefault=False, context=None)
For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse
object slightly modified.
< 出自: https://docs.python.org/3/library/urllib.request.html >

  • decode('utf-8')用来将页面转换成utf-8的编码格式,否则会出现乱码

二 模拟浏览器爬取信息

在访问某些网站的时候,网站通常会用判断访问是否带有头文件来鉴别该访问是否为爬虫,用来作为反爬取的一种策略。
先来看一下Chrome的头信息(F12打开开发者模式)如下:

Python 3 爬虫学习笔记 (一)_第1张图片
Paste_Image.png

如图,访问头信息中显示了浏览器以及系统的信息(headers所含信息众多,具体可自行查询)

Python中urllib中的request模块提供了模拟浏览器访问的功能,代码如下:

from urllib import request

url = 'http://www.baidu.com'
# page = request.Request(url)
# page.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36')
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
page = request.Request(url, headers=headers)
page_info = request.urlopen(page).read().decode('utf-8')
print(page_info)

可以通过add_header(key, value) 或者直接以参数的形式和URL一起请求访问,urllib.request.Request()

urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

其中headers是一个字典,通过这种方式可以将爬虫模拟成浏览器对网站进行访问。(https://docs.python.org/3/library/urllib.request.html?highlight=request#module-urllib.request )

你可能感兴趣的:(Python 3 爬虫学习笔记 (一))