未分类

jQuery基础选择器名称用法描述ID选择器$("#id")获取指定ID的元素类选择器$(".class")获取同一类的class的元素标签选择器$("div")获取同一类标签的所有元素全选选择器$("*")匹配所有元素并集选择器$("div,p,li")选取多个元素交集选择器$("li.current")交集元素jQuery层级选择器名称用法描述子代选择器$("ul>li");使用>查找下一级标签,不会获取孙子层元素后代选择器$("ulli");使用空格,代表获取ul下的所有li元素,包括孙子等jQuery筛选选择器语法用法描述:first$("li:first")选择第一个li标签:last$("li:last")选择最后一个li标签:eq(index)$("li:eq(0)")选择索引为0的li标签:odd$("li:odd")选择索引为奇数的li标签:even$("div,p,li")选择索引为偶数的li标签jQuery筛选方法selector代表选择器的意思语法用法描述parent()$("li").parent()查找父级元素children(selector)$("ul").children("li")相当于$("ul>li"),最近的一级find()$("ul").find("li")相当于后代选择器$("ulli")siblings(selector)$(".first").siblings("li")查找同级的li标签nextAll([expr])$("div").nextAll()查找当前元素之后的所有同级元素prevAll([expr])$("div").prevtAll([expr])查找当前元素之前的所有同级元素hasClass(class)$("divi").hasClass('pro')检查某个标签是否包含某个特定的class,有返回trueeq(index)$("div").eq(0)相当于$("div:eq(0)")标签过滤器小例子//查找div下的第一个li,设置为pink色$("divli:first").css("color","pink");//查找同级的所有标签$("span").siblings()//查找同级的所有标签$("span").siblings()

未分类

登录数据库Mysql为了安全,默认不允许远程用户root登录mysql-p[]-u[]-p[]mysql-hlocalhost-uroot-p参数作用-h主机地址:-p127.0.0.1:3306-u用户名:-uroot-p密码:-p密码查看数据库showdatabases;进入数据库use[数据库名];查看数据库的全部表第一种方法:首先要进入数据库:use[数据库名];然后查看表:showtables;第二种方法:直接查看showtablesfrom[数据库名];查看当前操作的数据库selectdatabase();mysql>selectdatabase();+------------+|database()|+------------+|news|+------------+1rowinset(0.00sec)创建数据库createdatabase[数据库名];删除数据库dropdatabaes[数据库名];退出Mysqlexitmysql>exitByeC:\Users\ASUS>打开数据库登录MySQL后,需要对数据库进行操作,例如查询、创建表等。需要先用use命令打开相应数据库,才能对该数据库进行后续操作。use[数据库名];mysql>usenews;Databasechangedmysql>创建数据库表打开相应数据库后,才能进行这项操作,最后一个字段不写逗号createtable[表名]([字段名1][类型1][类型2],[字段名2][类型1][类型2],....);createtablestudent(idint(4)primarykeyauto_increment,namechar(20)notnull,sexint(4)notnulldefault'0'#不写逗号);删除数据库表droptables[表名];droptablesstudent;查看MySQL的版本第一种方法:mysql>selectversion();+------------+|version()|+------------+|5.6.43-log|+------------+1rowinset(0.01sec)第二种方法:在CMD执行:mysql--version或者mysql-VC:\Users\ASUS>mysql--versionmysqlVer14.14Distrib5.6.43,forWin64(x86_64)

2019-11-21 820 1
未分类

迭代器迭代器就是可以使用for循环的对象,list、str、tuple….那怎样才能实现这样的迭代?nums=[12,13,14]strs="python"tuples=(1,2,3,4,5)fornuminnums:print(num)一个对象可迭代的条件需要这个对象有__iter__()方法classClassmate(object):#有了这个方法该类就是可迭代的def__iter__(self):pass添加一个列表和添加方法给Classmate类classClassmate(object):def__init__(self):#存储self.namesList=list()defadd(self,other):#添加到列表里self.namesList.append(other)#有了这个方法该类就是可迭代的def__iter__(self):pass迭代器一个对象有__iter__()和__next__()方法叫迭代器如果使该对象可以返回迭代的数据:就需要一个迭代器的__next__()方法定义一个迭代器类classClassIterator(object):def__iter__(self):passdef__next__(self):pass完善一个可以执行的迭代器迭代对象的__iter__()方法需要返回一个迭代器对象#可迭代对象classClassmate(object):def__init__(self):self.namesList=list()defadd(self,other):self.namesList.append(other)#有了这个方法该类就是可迭代的def__iter__(self):#需要反对一个迭代器对象#把self传给迭代器,使迭代器可以获取self.namesListreturnClassIterator(self)#迭代器对象classClassIterator(object):def__init__(self,obj):self.nameList=obj.namesList#记录循环的次数self.count=0def__iter__(self):passdef__next__(self):ifself.count<len(self.nameList):name=self.nameList[self.count]self.count+=1returnnameelse:#自定义一个异常停止循环raiseStopIteration#主函数classmate=Classmate()#实例化对象classmate.add("小小")classmate.add("大大")classmate.add("中中")#for循环对象fornameinclassmate:print(name)把迭代对象类和迭代器类合并迭代对象和迭代器是两个类,那是否可以合并classClassmate(object):def__init__(self):self.namesList=list()self.count=0defadd(self,other):self.namesList.append(other)#有了这个方法该类就是可迭代的def__iter__(self):#需要反对一个迭代器对象#把列表传给迭代器returnselfdef__next__(self):ifself.count<len(self.namesList):name=self.namesList[self.count]self.count+=1returnnameelse:#自定义一个异常停止循环raiseStopIteration

未分类

CrawlSpider简介Spider可以做很多爬虫了,但是CrawlSpider是为全站爬取而生创建CrawlSpider爬虫工程scrapystartprojectwxapp创建CrawlSpider爬虫scrapygenspider-tcrawl[爬虫名称][爬取网站的域名]scrapygenspider-tcrawlwxapp_spiderwxapp-union.com修改settings.py设置#设置user-agent#Crawlresponsiblybyidentifyingyourself(andyourwebsite)ontheuser-agentUSER_AGENT=''#关闭机器人协议#Obeyrobots.txtrulesROBOTSTXT_OBEY=False#设置延迟#Configureadelayforrequestsforthesamewebsite(default:0)#Seehttps://docs.scrapy.org/en/latest/topics/settings.html#download-delay#SeealsoautothrottlesettingsanddocsDOWNLOAD_DELAY=1#设置headers#Overridethedefaultrequestheaders:DEFAULT_REQUEST_HEADERS={'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language':'en',}#开启pipelines文件写入#Configureitempipelines#Seehttps://docs.scrapy.org/en/latest/topics/item-pipeline.htmlITEM_PIPELINES={'wxapp.pipelines.WxappPipeline':300,}制定Items传输打开items.pyclassWxappItem(scrapy.Item):#definethefieldsforyouritemherelike:#name=scrapy.Field()#文章标题title=scrapy.Field()#文章内容article=scrapy.Field()编写获取页面和文章链接的规则进入/spiders目录,查看wxapp_spider.py的爬虫类是继承于CrawlSpider类可在rules=()里定义多个Rule()规则Rule()参数详解:LinkExtractor(allow=r’匹配规则’):指定在页面里匹配链接的规则,支持正则表达式callback=’函数名称’:匹配到链接所执行的函数follow=True:爬取了匹配的页面后,是否在匹配页面再进行匹配(可实现翻页操作)name='wxapp_spder'allowed_domains=['www.wxapp-union.com']start_urls=['http://www.wxapp-union.com/portal.php?mod=list&catid=1&page=1']rules=(#设置匹配页数的规则(可以设置多个匹配连接的Rule())Rule(#页数的连接的匹配规则(支持正则表达式)LinkExtractor(allow=r'.+mod=list&catid=1&page=\d+'),#匹配到链接进行解析的函数follow=True),#匹配文章页面链接Rule(#匹配文章链接LinkExtractor(r'http://www.wxapp-union.com/article-(.*)-(.*)\.html'),#匹配到文章链接的解析函数callback='parse_article',follow=False,))添加解析文章页面的函数parse_article()导入fromwxapp.itemsimportWxappItemdefparse_item(self,response):pass#print(response.url)defparse_article(self,response):title=response.xpath('//div[@class="hhmcl"]/div/h1/text()').get()articleList=response.xpath('//td[@id="article_content"]//text()').getall()article="".join(articleList).split()#拼接返回的列表,去除前后空白字符yieldWxappItem(title=title,article=article)存储爬取数据打开pipeline.py文件导入fromscrapy.exportersimportJsonLinesItemExporter模块classWxappPipeline(object):defopen_spider(self,spider)::#以二进制方式打开文件self.ft=open('articleInfo.json','wb')self.exporter=JsonLinesItemExporter(self.ft,ensure_ascii=False,encoding='utf-8')defclose_spider(self,spider):self.ft.close()defprocess_item(self,item,spider):self.exporter.export_item(item)returnitem运行爬虫scrapycrawlwxapp_spider

未分类

0x00创建爬虫工程进入要创建爬虫的文件下,执行下面命令scrapystartprojectbigdataboy0x01创建爬虫项目进入爬虫工程目录,执行命令,创建第一个爬虫scrapygenspiderbigdataboy_spiderbigdataboy.cn0x02设置爬虫打开settings.py文件,取消下面代码的注释#开启pipelines功能#Configureitempipelines#Seehttps://docs.scrapy.org/en/latest/topics/item-pipeline.htmlITEM_PIPELINES={'bigdataboy.pipelines.BigdataboyPipeline':300,}#添加'User-Agent'#Crawlresponsiblybyidentifyingyourself(andyourwebsite)ontheuser-agentUSER_AGENT=''}0x03编写网页的解析打开bigdataboy_spider.py文件有一个defparse(self,response):函数:这个函数的response是Scrapy框架爬取网页的相应返回值,它是一个scrapy.http.response.html.HtmlResponse对象,所以可以使用xpath,css…提取数据#导入item模型frombigdataboy.itemsimportBigdataboyItemdefparse(self,response):#使用xpath解析网页articleUrl=response.xpath('//div[@class="item-desc"]/a/@href').extract()item=BigdataboyItem(url=articleUrl)#使用定义的item定义的传输参数进行传递yielditem#获取下一页的连接nextUrl=response.xpath('//*[@id="pagenavi"]/div/ol//*[@class="next"]/a/@href').get()#print(nextUrl)ifnextUrl:#传入连接,然后执行的函数yieldscrapy.Request(nextUrl)else:return0x04定义item模型打开items.py文件classBigdataboyItem(scrapy.Item):#definethefieldsforyouritemherelike:#name=scrapy.Field()url=scrapy.Field()#自定义的模型0x05导出数据打开pipeline.py文件fromscrapy.exportersimportJsonItemExporterclassBigdataboyPipeline(object):def__init__(self):self.openFile=open("url.json","wb")#需要使用二进制打开文件,因为在导出过程中是使用的[字节]方式#传入文件打开对象self.exporter=JsonItemExporter(self.openFile)#准备导出self.exporter.start_exporting()#爬虫开始执行调用这个函数defopen_spider(self,spider):print("爬虫开始执行")defprocess_item(self,item,spider):#导出数据self.exporter.export_item(item)returnitem#爬虫执行结束调用这个函数defclose_spider(self,spider):#完成导出self.exporter.finish_exporting()#关闭文件打开self.openFile.close()print("爬虫执行完成")0x06运行爬虫执行命令在Pycharm的Terminal里执行scrapycrawlbigdataboy_spider查看运行结果

未分类

项目背景我们可以通过爬虫来模拟登录来查询自己的成绩,这其中最重要的就是登录这个关卡,只要通过了,就可以方便的查询自己的成绩了。但是我们还是要在法律的允许条件下爬取数据,下列的代码已进行隐私处理,并不针对任何组织。爬虫分析通过抓包,发现登录需要提交学号、密码、验证码、VIEWSTATE通过分析发现其中的VIEWSTATE参数就在网页中,所以我们可以通过正则表达式匹配出来爬虫项目结构importreimportrequestsclassAPI(object):...classTool(object):...API类·通过抓包,知道了以下接口classAPI(object):#登录页GET_INDEX="http://XXXXXXXX:XXXX/"#获取验证码GET_YZM_URL='http://XXXXXXXX:XXXX/CheckCode.aspx'#登录POST_LOGIN='http://XXXXXXXX:XXXX/default2.aspx'Tool类classTool(object):session=requests.session()VIEWSTATE=""#获取VIEWSTATE参数@classmethoddefgetHtml(cls):response=cls.session.get(API.GET_INDEX).textcls.VIEWSTATE=re.search(r'__VIEWSTATE"value="(.*?)"/>',response).group(1)#下载验证码在当前路径@classmethoddefdownload_yzm(cls):yzm_image=cls.session.get(url=API.GET_YZM_URL)withopen("yzm.jpg",'wb')asfile:file.write(yzm_image.content)#登录方法@classmethoddeflogin(cls,account,pwd,yzm):data={"__VIEWSTATE":cls.VIEWSTATE,"TextBox1":account,"TextBox2":pwd,"TextBox3":yzm,"RadioButtonList1":"%D1%A7%C9%FA","Button1":"",}response=cls.session.post(url=API.POST_LOGIN,data=data)response.encoding=response.apparent_encodingresponse=response.texttry:message=re.search(r">alert\('(.*?)'\);</script>",response).group(1)except:#登录成功跳转到详情页xm=re.search(r'<spanid="xhxm">(.*?)同学</span>',response).group(1)print("欢迎"+xm+"登录成功")else:#打印出登录失败信息print(message)主函数defmain():t=Tool()#实例化类t.getHtml()#获取VIEWSTATEt.download_yzm()#下载验证码account=input("请输入你的学号:")pwd=input("请输入你的密码:")yzm=input("请输入验证码:")t.login(account,pwd,yzm)#运行登录方法

2019-10-28 1086 0
未分类

需要导入的包注意导入mapreduce的新版本包带mapreduce的importorg.apache.hadoop.conf.Configuration;importorg.apache.hadoop.fs.Path;importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.mapreduce.Job;importorg.apache.hadoop.mapreduce.Mapper;importorg.apache.hadoop.mapreduce.Reducer;importorg.apache.hadoop.mapreduce.lib.input.FileInputFormat;importorg.apache.hadoop.mapreduce.lib.output.FileOutputFormat;importjava.io.IOException;MapReduce程序结构publicclassWordCountApp{//进行分割的map类publicstaticclassMyMapperextendsMapper<LongWritable,Text,Text,LongWritable>{......}//归并操作的Reducer类publicstaticclassMyReducerextendsReducer<Text,LongWritable,Text,LongWritable>{......}//定义Drive类(main类)publicstaticvoidmain(String[]args)throwsException{......}}map类:对读取的每一行单词进行分割操作,形成键值对Reducer类:把分割完成的键值对-->key,value,进行归并求和并输出Drive类:设置MapReduce作业提交、数据的输入路径、map的处理类、Reducer的处理类、数据的输出路径map分割操作的详解Mapper类四个泛型参数前两个参数为map输入类型,后两个参数为map的输出类型LongWritable:输入数据的首行的偏移量(相当于Java的Long类型)Text:输入的每一行的数据(相当于Java的String类型)Text:分割之后产生的键值对键的类型LongWritable:分割之后产生的键值对值的类型publicstaticclassMyMapperextendsMapper<LongWritable,Text,Text,LongWritable>{/**reduce参数:*LongWritablekey:输入数据的行的偏移量*Textvalue:读取的每一行数据*Contextcontext上下文连接**/@Overrideprotectedvoidmap(LongWritablekey,Textvalue,Contextcontext)throwsIOException,InterruptedException{//接收到的每一行数据,转化成Java的字符串Stringline=value.toString();//把字符串进行空格分隔,返回一个数组String[]words=line.split("");//返回字符串数组//利用循环使用context.write(key,value);组合成k,v形式for(Stringword:words){//通过context(上下文连接)把map分割的k、v输出context.write(newText(word),newLongWritable(1));//前面设置了返回值为Text,LongWritable类型}}}Reducer归并操作的详解Reducer类四个泛型参数前两个参数为Reducer输入类型,后两个参数为Reducer的输出类型Text:map的输出类型,就是Reduse的输入类型LongWritable:map的输出类型,就是Reduse的输入类型Text:进行归并操作之后的键值对-->键的类型LongWritable:进行归并操作之后的键值对-->的值类型publicstaticclassMyReducerextendsReducer<Text,LongWritable,Text,LongWritable>{/**reduce参数:*Textkey:Map操作后的键值对的键*Iterable<LongWritable>values:当进行Map操作之后,一个键可能有很多对应的值所以是一个迭代类型*Contextcontext上下文连接**/@Overrideprotectedvoidreduce(Textkey,Iterable<LongWritable>values,Contextcontext)throwsIOException,InterruptedException{//这里只需要把出现的迭代类型进行求和longsum=0;for(LongWritablevalue:values){//把LongWritable转成Java的数据类型进行求和sum+=value.get();}//最终的统计结果通过上下文连接输出context.write(key,newLongWritable(sum));}}定义Drive类(main类)publicstaticvoidmain(String[]args)throwsException{//抛出异常//创建一个Configuration对象Configurationconfiguration=newConfiguration();//注意是hadoop里的//创建一个Job,如有异常,先把异常抛出Jobjob=Job.getInstance(configuration,"wordCount");//设置Job的处理类job.setJarByClass(WordCountApp.class);//类名称//设置需要处理数据的输入路径FileInputFormat.setInputPaths(job,newPath(args[0]));//路径通过脚本参数传入//设置map的处理主类job.setMapperClass(MyMapper.class);//指定Mapper处理类job.setMapOutputKeyClass(Text.class);//设置map处理类的k输出类型job.setMapOutputValueClass(LongWritable.class);//设置map处理类的v输出类型//设置reducer的处理主类job.setReducerClass(MyReducer.class);//指定Reduse处理类job.setOutputKeyClass(Text.class);//设置reducer处理类的k输出类型job.setOutputValueClass(LongWritable.class);//设置reducer处理类的v输出类型//设置作业的输出路径FileOutputFormat.setOutputPath(job,newPath(args[1]));//路径通过脚本参数传入//提交作业booleanb=job.waitForCompletion(true);//参数为true确定提交//退出程序System.exit(b?0:1);//程序推出的状态码0正常}上传到hadoop执行首先把程序打成jar包。idea打jar教程hadoop执行jar命令:hadoopjarJar名称输入路径输出路径hadoopjarhadooptrain.jarhdfs://192.168.5.137:9000/words.txthdfs://192.168.5.137:9000/output执行结果