Python Selenium爬取数据
最近公司有一项Python爬取数据的工作,借鉴以往的代码将爬虫重新更新并整理
将现有爬虫分成几部分
0.文件读取器
其实文件读取和4中的文件存储是在一个部分的
这里简单介绍下xls的读取
defdeal_xls_col(name,sheet_name):
body=xlrd.open_workbook(name)
try:
sh=body.sheet_by_name(sheet_name)
except:
print"EORR"
returnsh.col_values(0)格式请忽略
这里读取了一竖行的xls的数据
返回的格式为list
1.总调度器
这里主要是写逻辑,及0234的顺序。
2.网页下载器
网页下载器主要是来模拟浏览器访问对应url
一个简单的例子
classHtmlDownloader(object):
defdownload(self,url):
ifurlisNone:
returnNone
response=urllib2.urlopen(url,timeout=300)
ifresponse.getcode()!=200:
returnNone
returnresponse.read()
例子只是去访问url并没有对cookie等相关限制信息做处理(需要请自行添加)
3.网页分析器
网页分析器其实就是来处理下载器返回的html的源码,比如用selenium来处理的话则有
company_info_text=driver.find_element_by_class_name('company_info_text')
company_text=driver.find_element_by_class_name('rowb-c-whitecompany-content')
就是用selenium的一些方法来获取你需要的数据而已
4.文件存储器
这里以xls为例:
defcreat_xls_6(xls_name):
styleBoldRed=xlwt.easyxf('font:color-indexred,boldon')
headerStye=styleBoldRedwb=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)
创建xls表格
definsert_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)
插入数据到表格
这里面没有什么高深的秘密,只要你封装好自己的函数就好了
上面的例子还不是最好的版本,因为每次使用都要重新修改,应该传入一个数据来代替那些变量,这样就可以适配各种数据的表格创建和添加了
还有要说的就是:一些网站会限制你爬取数据,但是大多数网站都是友好的,但是这并不表示你可以肆无忌惮的毫无限制的去爬取。爬取的时间最好设置成晚上或者。。。。
还有就是不要对目标网站造成不必要的‘伤害’。
爬虫并不难,且行且珍惜!
以上内容为大家介绍了PythonSelenium爬取数据,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

猜你喜欢LIKE
相关推荐HOT
更多>>
python调用dll
在python中调用dll文件中的接口比较简单,实例代码如下:如我们有一个test.dll文件,内部定义如下:extern"C"{int__stdcalltest(void*p,intlen)...详情>>
2023-11-08 23:31:04
pythonpathlib模块的用法有哪些?
python中pathlib模块的用法有哪些?在这个世界上,人们每天都在用Python完成着不同的工作。而文件操作,则是大家最常需要解决的任务之一。使用Py...详情>>
2023-11-08 18:37:21
pythonPyramid框架是什么?
python中Pyramid框架是什么?本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明Pyramid以其高效率和快节奏的开发能力而出名。P...详情>>
2023-11-08 08:56:32
pythongil是什么
pythongil是什么1、说明是全局解释器锁,每个线程在执行时候都需要先获取GIL,保证同一时刻只有一个线程可以执行代码,即同一时刻只有一个线程...详情>>
2023-11-08 05:44:47热门推荐
技术干货






