Scrapy-爬虫介绍

爬虫基本操作

  1.应用

    - 舆情系统:监听各大门户网站的热门词条、热门新闻,做进一步分析处理和展示

2.爬虫

  -  定向

  - 非定向

3.

  - 下载页面:

      http://www.autohome.com.cn/news/

  - 筛选:

      正则表达式

  ======= 开源模块 =======

  1.requests

    pip3 install requests

    response = requests.get('http://www.autohome.com.cn/news/')

    response.text  #str类型,用于接收html内容

    response.content  #字节类型,用于接收图片视频内容

    response.cookies.get_dict()  #获取cookies

    response.encoding

    response.apparent_encoding

    response.status_code

  2.beautifulsoup

    pip3 install BeautifulSoup4

    from bs4 import BeautifulSoup 

    soup = BeautiSoup(response.text,features='html.parser')  #将html转换为对象,对象嵌套对象

    target = soup.find(id='auto-channel-lazyload-article')

    print(target)

    总结:

      soup.find('div')

      soup.find(id='asdf')

      soup.find('div',href='asdf')  #标签和标签属性组合使用进行find

      find():懒惰查找,返回的是soup对象;find_all():全部查找,返回的是列表

      obj1 = soup.find.('div')

      obj1.text ##获取文本

      obj.attrs.get('href')  ##获取href属性的值

爬虫并发方案

    - 异步IO:gevent/Twisted/asyncio/aiohttp

    - IO多路复用:select

Scrapy框架

    - 异步IO:Twisted

 

Scrapy框架:

1.下载页面

2.解析

3.并发

4.深度(递归、循环)

安装:http://www.cnblogs.com/wupeiqi/articles/6229292.html
Linux
pip3 install scrapy

Windows
a. pip3 install wheel
b. 下载twisted http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
c. 进入下载目录,执行 pip3 install Twisted‑17.1.0‑cp35‑cp35m‑win_amd64.whl
d. pip3 install scrapy
e. 下载并安装pywin32:https://sourceforge.net/projects/pywin32/files/

使用:
指定初始URL

scrapy startproject proscrapy

scrapy genspider baidu baidu.com

scrapy crawl baidu --nolog  #不打印日志

编写代码:

1.name不能省略

2.start_urls起始url

3.allowed_domains 允许爬取的域名

4.重写start_requests,指定初始处理请求的函数

  def start_requests(self):

    for url in self.start_urls:

      yield Request(url,callback=self.parse)

5.响应response:

  response.url

  response.text

  response.body

  response.meta  #返回一个字典包括当前深度depth

6.采集数据:

  Selector(response=response).xpath()

  //div[@id='i1']

  //div[starts-with(@href,"/all/hot/recent/")]

  //div[re:test(@href,"/all/hot/recent/")]

  // 表示子孙
  .// 表示当前对象的子孙中
  / 表示儿子
  ./表示当前对象的儿子中
  /div 表示儿子中的div标签
  /div[@id="i1"] 表示儿子中的div标签且id=i1
  //div 表示子子孙孙中的div标签
  obj.extract() 对象转换成字符串,返回列表
  obj.extract_first() 对象转换成字符串,返回列表中的第一个元素
  //div/text() 获取div标签的文本
7. 解析响应内容,给调度器

  yield Request(url='"",callback='parse')

  yield Item(name="",tittle="")  #给item做格式化;pipeline做持久化

8.url去重:

  setting中配置DUPEFILTER_CLASS = "pro_scrapy.duplication.RepeatFilter"

9.pipeline:

  from scrapy.exceptions import DropItem   

    raise DropItem()  #丢弃掉item不传给下一个pipeline

  else:
    return item  #把item交给下一个pipeline处理

  

 

 

# -*- coding: utf-8 -*-
import scrapy
import sys,io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') #Windows下运行要加上这句
class ChoutiSpider(scrapy.Spider): name = 'baidu' allowed_domains = ['baidu.com'] start_urls = ['http://baidu.com/']
def parse(self, response):
content = str(response.body,encoding='utf-8') #Windows下运行要加上这句
#print(content)
#找到文档中所有a标签
hxs = Selector(response=response).xpath('//a') #标签对象列表
for i in hxs:
print(i) #标签对象

 



 

posted @ 2018-07-08 14:58  benchdog  阅读(147)  评论(0编辑  收藏  举报