您的位置:首页 > 编程语言 > Python开发

简单Python3爬虫程序(5)进阶:知乎网的登录与用户相关信息爬取

2016-04-12 09:59 661 查看
下面是在Python3上的代码,这次觉得麻烦就没有分成两个模块了,本来想爬的是每个用户的主页,但是正则没有写好,所以就爬取了所有与用户相关的信息:

import gzip
import re
from collections import deque
import http.cookiejar
import urllib.request
import urllib.parse
queue = deque()
visited = set()
def ungzip(data):
try:
print('正在解压.....')
data = gzip.decompress(data)
print('解压完毕!')
except:
print('未经压缩, 无需解压')
return data

def getXSRF(data):
cer = re.compile('name=\"_xsrf\" value=\"(.*)\"', flags = 0)
strlist = cer.findall(data)
return strlist[0]

def getOpener(head):
# deal with the Cookies
cj = http.cookiejar.CookieJar()
pro = urllib.request.HTTPCookieProcessor(cj)
opener = urllib.request.build_opener(pro)
header = []
for key, value in head.items():
elem = (key, value)
header.append(elem)
opener.addheaders = header
return opener
header = {
'Connection': 'Keep-Alive',
'Accept': 'text/html, application/xhtml+xml, */*',
'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Accept-Encoding': 'gzip, deflate',
'Host': 'www.zhihu.com',
'DNT': '1'
}

url = 'http://www.zhihu.com/'
opener = getOpener(header)
op = opener.open(url)
data = op.read()
data = ungzip(data)
_xsrf = getXSRF(data.decode())

url += 'login/email'
id = '账号'
password = '密码'
postDict = {
'_xsrf':_xsrf,
'email': id,
'password': password,
'rememberme': 'y'
}
postData = urllib.parse.urlencode(postDict).encode()
op = opener.open(url,data=postData)
data = op.read()
data = ungzip(data)
saveFile(data)

url = 'http://www.zhihu.com/'
queue.append(url)
cnt = 1
while queue:
url = queue.popleft()
visited |= {url}
print('已经抓取第: ' , cnt, '个链接','   当前链接:  ' + url)
op = opener.open(url)
if 'html' not in op.getheader('Content-Type'):
continue
try:
data = ungzip(op.read())
saveFile(data)
data = data.decode(encoding='UTF-8')
print('save the :',cnt,' data')
except:
continue

cnt += 1
linkre = re.compile('href=\"(.+?)\"')
try:
for x in linkre.findall(data):
if 'http' in x and 'zhihu.com/people' in x  and x not in visited:
queue.append(x)
print('把 ' + x +'加入队列')
except:
continue

其中saveFile函数请见简单Python3爬虫程序(4),欢迎留言!

我们要把要 POST 的数据弄成 opener.open() 支持的格式. 所以还要 urllib.parse 库里的 urlencode() 函数. 这个函数可以把字典、元组、集合类型的数据转换成 & 连接的 str,然后通过 encode() 来编码, 才能当作 opener.open() 或者 urlopen() 的 POST 数据参数来使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: