【爬虫】python selenium 爬取数据

最近公司有一项爬取数据的工作,借鉴以往的代码将爬虫重新更新并整理
将现有爬虫分成几部分
0.文件读取器
其实文件读取和4中的文件存储是在一个部分的
这里简单介绍下xls的读取
<code>
def deal_xls_col(name,sheet_name):
body = xlrd.open_workbook(name)
try:
sh = body.sheet_by_name(sheet_name)
except:
print “EORR”
return sh.col_values(0)</code>格式请忽略
这里读取了一竖行的xls的数据
返回的格式为list

  1. 总调度器
    这里主要是写逻辑,及0234的顺序。

2.网页下载器
网页下载器主要是来模拟浏览器访问对应url
一个简单的例子
<code>
class HtmlDownloader(object):
def download(self,url):
if url is None:
return None
response = urllib2.urlopen(url,timeout=300)
if response.getcode() != 200:
return None
return response.read()
</code>
例子只是去访问url并没有对cookie等相关限制信息做处理(需要请自行添加)

3.网页分析器
网页分析器其实就是来处理下载器返回的html的源码,比如用selenium来处理的话则有
<code>
company_info_text = driver.find_element_by_class_name(‘company_info_text’)
company_text = driver.find_element_by_class_name(‘row b-c-white company-content’)
</code>
就是用selenium的一些方法来获取你需要的数据而已

4.文件存储器
这里以xls为例:
<code>
def creat_xls_6(xls_name):
styleBoldRed = xlwt.easyxf(‘font:color-index red, bold on’)
headerStye = styleBoldRed wb = xlwt.Workbook()
ws = wb.add_sheet(xls_name)
ws.write(0, 0, “name”, headerStye)
ws.write(0, 1, “oper_name”, headerStye)
ws.write(0, 2, “start_date”, headerStye)
ws.write(0, 3, “xfsSearchStatus”, headerStye)
wb.save(xls_name)
</code>
创建xls表格
<code>
def insert_xls_6(xls_name,id, name, oper_name, start_date,xfsSearchStatus):
oldWb = xlrd.open_workbook(xls_name)
newWb = copy(oldWb)
newWs = newWb.get_sheet(0)
newWs.write(id, 0, name)
newWs.write(id, 1, oper_name)
newWs.write(id, 2, start_date)
newWs.write(id, 3, xfsSearchStatus)
newWb.save(xls_name)
</code>
插入数据到表格
这里面没有什么高深的秘密,只要你封装好自己的函数就好了
上面的例子还不是最好的版本,因为每次使用都要重新修改,应该传入一个数据来代替那些变量,这样就可以适配各种数据的表格创建和添加了

还有要说的就是:一些网站会限制你爬取数据,但是大多数网站都是友好的,但是这并不表示你可以肆无忌惮的毫无限制的去爬取。爬取的时间最好设置成晚上或者。。。。
还有就是不要对目标网站造成不必要的‘伤害’。

爬虫并不难,且行且珍惜!

2016.11.10晚

    原文作者:风雨byt
    原文地址: https://www.jianshu.com/p/7091f7955769
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞