在重构人人贷爬虫的过程中,主要要爬取的数据是以json数据的格式呈现的,要提取的html内容如下:
在之前的版本中,应用了re进行简单粗暴的正则匹配,效率较低,因此在重构过程中,将使用BS4对这个标签进行提取,之后应用json库将string转为dict,便于后面的调用和输出。
下面简单介绍一下应用到的方法:
# ! /usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = \'Gao Yuhao\'
# 统一 Python 2 和 3 的语法
try:
input = raw_input
except:
pass
import requests
from bs4 import BeartifulSoup
import json
# 确定测试爬虫页面
page_index = input(\'Pls input the page_index you want to try:\')
surl = \'http://www.we.com/lend/detailPage.action?loanId=\' + page_index
# 使用requests获取网页
req = requests.get(url = surl)
html = req.text.encode(\'utf-8\')
# 使用BS提取内容
soup = BeautifulSoup(html)
res = soup(\'script\',id = \'credit-info-data\')[0].text
# 使用json将其转换为dict
res_json = json.loads(res)
print json.dumps(res_json, indent = 4)
上一篇:Scikit-learn使用总结
下一篇:Python的鸭子类型