| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- #-*-coding:utf-8-*-
- #支持中文必须加上上面一句话
- __author__ = 'Administrator'
- import scrapy
- #正则表达式模块
- import re
- #包含scrapy中的Request请求,在yield request中用到
- from scrapy.http import Request
- #引入将要保存到数据库的类名称
- from ApiCrawler.items import ApiItem
- class ApiSpider(scrapy.spiders.Spider):
- name = "api"
- #只爬api.1473.cn网址
- allowed_domains=["api.1473.cn"]
- #开始爬的网址
- start_urls=[
- "http://api.1473.cn"
- ]
- #目的是去除重复的url。
- URLS=[]
- #计数,一共爬了多少次
- count=0
- def parse(self, response):
- #allUrl=response.url
- #print allUrl
- #从response中获取内容,保存到数据库,为什么能保存到数据库呢?应该是架构写好的。
- #extract方法返回unicode字符串
- apiItem=ApiItem()
- apiItem['url'] = response.url
- # normalize-space 解决xpath取出的title值有很多回车空格的问题
- #text()函数获取标签下面的文本
- _titles=response.xpath(' normalize-space(/html/head/title/text())')
- if _titles:
- apiItem['title'] =_titles[0].extract()
- else:
- apiItem['title'] =""
- #获取meta中的content比较麻烦,国内居然没有资料。
- _keywords=response.xpath("//meta[@name='keywords']/@content")
- if _keywords:
- apiItem['keywords'] = _keywords[0].extract()
- else:
- apiItem['keywords'] = ""
- _description=response.xpath("//meta[@name='description']/@content")
- if _description:
- apiItem['description'] = _description[0].extract()
- else:
- apiItem['description']=""
- #首先获取body标签,然后再获取body标签中的所有字符串,为节约代码,下面使用三元操作符号,不熟悉的学生去学习一下三元
- #python的三元比较奇葩,估计是不入流程序员写的,h = "变量1" if a>b else "变量2"
- #_content=response.xpath('/html/body').xpath('string(.)').extract()[0];
- _content=response.xpath('/html/body').xpath('string(.)')
- #_content=response.xpath("//div[@class='book']").xpath('string(.)')
- apiItem['content']=_content[0].extract() if _content else ""
- yield apiItem
- # 下面的正则会提取页面中所有的后缀名为.aspx,.html .htm的超级链接,然后循环递归
- pattern=re.compile(r'((((https|http):\/\/)|\/)[0-9a-zA-Z\/\.@-_%]*?\.(aspx|html|htm))')
- urls=pattern.findall(response.text)
- for url in urls:
- #去除重复
- findUrl=url[0]
- if findUrl in self.URLS:
- continue
- else:
- self.URLS.append(findUrl)
- #Request对象需要包含from scrapy.http import Request
- #递归获取
- yield Request(findUrl,callback=self.parse)
- #filename=response.url.split("/")[2]
- #with open(filename,'wb') as f:
- # f.writable(response.body)
|