听说Python爬虫知网很火,我今天就做一个。
上代码:
import requests
import re
import time
import xlrd
from xlrd import open_workbook
from xlutils.copy import copy
class BeautifulPicture():
def get_pic(self):
data = xlrd.open_workbook(r'C:\\flim\library_my\new.xls') # 打开xls文件,自己新建这个文件在运行路径,不然不行的哦
table = data.sheets()[0] # 打开第一张表
table2 = data.sheets()[1] # 打开第一张表
i = table.nrows #上一次爬到的表1的行数
i1 = 0
i2 = table2.nrows #上一次爬到的表2的行数
told = 0
rb = open_workbook(r'C:\\flim\library_my\new.xls','utf-8')
wb = copy(rb) # 将上一次爬到的复制到新表里,并在新表里继续添加纪录
# 通过get_sheet()获取的sheet有write()方法
ws = wb.get_sheet(0)
ws1 = wb.get_sheet(1)
p = 1 # 这里是页数
for num in range(p, p + 100):
# 这里的num是页码
web_url ='http://kns.cnki.net/kns/brief/brief.aspx?curpage=%s&Reco' \
'rdsPerPage=50&QueryID=8&ID=&turnpage=1&tpagemode=L&dbPref' \
'ix=SCDB&Fields=&DisplayMode=listmode&PageName=ASP.brief_' \
'default_result_aspx#J_ORDER&' % num #这里的URL实现了二次加载
print('搜素页的URL=',web_url)
# 这里开始是时间控制
t = int(time.clock())
print(t / 60, '分钟')
useTime = t - told
# 如果一个周期的时间使用太短,则等待一段时间
# 主要用于防止被禁
if (useTime < 120 and useTime > 10):
print("useTime=%s" % useTime)
whiteTime = 120 - useTime
print("等待%s秒" % whiteTime)
time.sleep(whiteTime)
told = int(time.clock())
print(t)
print('开始网页get请求')
r = self.request(web_url