请注意,本文介绍如何用python3来进行爬虫。下面介绍需要用到的模块和工具。
模块:
相比于python2,python3有些模块进行了改动,以下是会用到的模块的改动说明:
- Python2的urllib2模块合并到了urllib
- urlopen的使用包的位置为urllib.request.urlopen
- urlencode使用包位置为urllib.parse.urlencode
- cookielib变更为http.cookiejar
网站分析工具:
分析目标web的登录页面,主要获取登录时向服务器传递的格式及参数名
- 比如chrome浏览器自带的开发者工具(F12)
- Fiddler抓包工具(这里主要使用该工具)
- FireFox的FireBug等
1. 一个简单的抓取网页信息的程序
import urllib.request
import urllib.error
url = 'http://www.baidu.com'
req = urllib.request.Request(url) # 返回一个request的实例
try:
response = urllib.request.urlopen(req)
html = response.read() # 或者直接将html写入txt文件,将txt中的内容拷入html在线运行工具,运行后看页面效果
fout = open('html.html', 'wb') # 由于网页抓取下来的是bytes格式的数据,所以写入文件时需要以二进制的方式写入
try:
fout.write(html)
print('Done')
except Exception as e:
print('Error')
finally:
fout.flush()
fout.close() # 关闭文件
except urllib.Error.URLError as e:
print(e.code,':',e.reason)
程序运行成功后,打开html.html文件,会得到和百度主页一样的网页。说明爬取百度主页成功。
那如果碰到需要输入用户名、密码和验证码后才能登陆的情况,如何解决呢?下面继续分析。
2. cookie模拟登陆
- 保存cookie
import urllib.request
import urllib.parse
import urllib.error
import http.cookiejar
filename = 'cookie.txt' # 用于保存cookie
url = 'http://www.baidu.com'
cookie = http.cookiejar.MozillaCookieJar(filename) # 声明MozillaCookieJar对象实例来保存cookie
handler = urllib.request.HTTPCookieProcessor(cookie) # 创建cookie处理器
opener = urllib.request.build_opener(handler) # 通过handler来创建opener
request = urllib.request.Request(url) # Request对象实例化
try:
response = opener.open(request) # urlopen是一个封装好的openerDirector实例
page = response.read() # 读取抓取的网页内容
file_out = open('html.html', 'wb')
try:
file_out.write(page)
print('Done!')
except Exception as e:
print('Fail to write.')
finally:
file_out.flush()
file_out.close()
except urllib.error.URLError as e: # 抛出URL异常
print(e.reason)
cookie.save(ignore_discard=True, ignore_expires=True)
for item in cookie:
print('Name = ' + item.name)
print('Value = ' + item.value)
程序的输出结果应该为
Name = BAIDUID
Value = D3B95998C4E30EABBE5A23BA140F7FE3:FG=1
Name = BIDUPSID
Value = D3B95998C4E30EABBE5A23BA140F7FE3
Name = H_PS_PSSID
Value = 1421_21106_17001
Name = PSTM
Value = 1502343810
Name = BDSVRTM
Value = 0
Name = BD_HOME
Value = 0
打开html.html,如果是百度主页,说明爬取程序运行成功。
- 使用已有的cookie登陆网站
以【https://www.caifupad.com】为例,首先随便注册一个账号。通过Fiddler抓取登陆账号时的web信息。
如下图Fiddler的截屏所示,可以获得如下信息:
1. 真实的登陆地址是 https://www.caifupad.com/user/login
2. Body中的信息就是postdata,包括loginName和loginPass
3. 登陆成功后的网站响应消息如XML界面所示
["{\"id\":\"unlogin\",\"isSuccess\":true,\"info\":\"\"}","{\"id\":\"pwlogin\",\"isSuccess\":true,\"info\":\"密码格式不正确\"}","{\"pastUrl\":null,\"isSuccess\":true,\"info\":\"登陆成功\"}"]
![](https://img-my.csdn.net/uploads/201708/10/1502355475_9381.png)
下面就是具体的代码
import urllib.request
import urllib.parse
import urllib.error
import http.cookiejar
test_url = 'https://www.caifupad.com/person/account/overview' # 验证网站
cookie = http.cookiejar.MozillaCookieJar('cookie.txt')
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
request = urllib.request.Request(test_url)
try:
response = opener.open(request)
page = response.read()
f_out = open('html.html', 'wb')
f_out.write(page)
f_out.close()
except urllib.error.URLError as e:
print(e.reason)
for item in cookie:
print('Name = ' + item.name)
print('Value = ' + item.value)
最后在看一下得到的html.html,效果应该如下所示
![](https://img-my.csdn.net/uploads/201708/10/1502356124_6042.png)
可以看到用户名zai123,说明通过使用cookie登陆网站这种方法成功了。
至于为什么网页界面和原网页不同,主要原因是原网页的图片是引用的本地路径。