爬虫

爬虫

 

网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。

Requests

Python标准库中提供了:urllib、urllib2、httplib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

import urllib2
import json
import cookielib


def urllib2_request(url, method="GET", cookie="", headers={}, data=None):
    """
    :param url: 要请求的url
    :param cookie: 请求方式,GET、POST、DELETE、PUT..
    :param cookie: 要传入的cookie,cookie= 'k1=v1;k1=v2'
    :param headers: 发送数据时携带的请求头,headers = {'ContentType':'application/json; charset=UTF-8'}
    :param data: 要发送的数据GET方式需要传入参数,data={'d1': 'v1'}
    :return: 返回元祖,响应的字符串内容 和 cookiejar对象
    对于cookiejar对象,可以使用for循环访问:
        for item in cookiejar:
            print item.name,item.value
    """
    if data:
        data = json.dumps(data)

    cookie_jar = cookielib.CookieJar()
    handler = urllib2.HTTPCookieProcessor(cookie_jar)
    opener = urllib2.build_opener(handler)
    opener.addheaders.append(['Cookie', 'k1=v1;k1=v2'])
    request = urllib2.Request(url=url, data=data, headers=headers)
    request.get_method = lambda: method

    response = opener.open(request)
    origin = response.read()

    return origin, cookie_jar


# GET
result = urllib2_request('http://127.0.0.1:8001/index/', method="GET")

# POST
result = urllib2_request('http://127.0.0.1:8001/index/',  method="POST", data= {'k1': 'v1'})

# PUT
result = urllib2_request('http://127.0.0.1:8001/index/',  method="PUT", data= {'k1': 'v1'})

封装urllib

urllib urllib2的get 传参方式

    def _urllib2_request(self, url, method="GET", headers={}, data=None):
        if data:
            data = json.dumps(data)
        if method == "GET":
            url = url + "?" + urllib.urlencode(json.loads(data))
            print 49, url
            request = urllib2.Request(url)
        else:
            request = urllib2.Request(url=url, data=data, headers=headers)
        request.get_method = lambda: method
        response = urllib2.urlopen(request, timeout=3)
        return response



signature = self._signature_info()
        args = {
            "domain": self._domain,
            "sign": signature,
        }
        response = self._urllib2_request(
            self.YfcloudUrl,
            data=args
        )
            # except Exception, e:
            #     logger.LOG.error("gosun request failed. %s" % str(e))
            # else:
        if response.code != 200:
            logger.LOG.error("gosun request failed, status code: %s, %s"
                             % (response.status_code, self._domain))
        else:
            resp = response.read()
            resp = json.loads(resp)
            if not isinstance(resp, dict):
                logger.LOG.error(
                    "gosun request response error: %s" % (resp, self._domain))
            if len(resp) != 0:
                result = resp

POST方式:

上面我们说了data参数是干嘛的?对了,它就是用在这里的,我们传送的数据就是这个参数data,下面演示一下POST方式。

 

 

我们引入了urllib库,现在我们模拟登陆CSDN,当然上述代码可能登陆不进去,因为CSDN还有个流水号的字段,没有设置全,比较复杂在这里就不写上去了,在此只是说明登录的原理。一般的登录网站一般是这种写法。

我们需要定义一个字典,名字为values,参数我设置了username和password,下面利用urllib的urlencode方法将字典编码,命名为data,构建request时传入两个参数,url和data,运行程序,返回的便是POST后呈现的页面内容。

注意上面字典的定义方式还有一种,下面的写法是等价的

 

 

以上方法便实现了POST方式的传送

GET方式:

至于GET方式我们可以直接把参数写到网址上面,直接构建一个带参数的URL出来即可。

 

 

你可以print geturl,打印输出一下url,发现其实就是原来的url加?然后加编码后的参数

 

 

和我们平常GET访问方式一模一样,这样就实现了数据的GET方式传送。

本节讲解了一些基本使用,可以抓取到一些基本的网页信息,小伙伴们加油!

 

 

REQUESTS模块  

Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的 完成浏览器可有的任何操作。

1、GET请求

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 1、无参数实例
  
import requests
  
ret = requests.get('https://github.com/timeline.json')
  
print ret.url
print ret.text
  
  
  
# 2、有参数实例
  
import requests
  
payload = {'key1''value1''key2''value2'}
ret = requests.get("http://httpbin.org/get", params=payload)
  
print ret.url
print ret.text

 

 向 https://github.com/timeline.json 发送一个GET请求,将请求和响应相关均封装在 ret 对象中。

2、POST请求

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 1、基本POST实例
  
import requests
  
payload = {'key1''value1''key2''value2'}
ret = requests.post("http://httpbin.org/post", data=payload)
  
print ret.text
  
  
# 2、发送请求头和数据实例
  
import requests
import json
  
url = 'https://api.github.com/some/endpoint'
payload = {'some''data'}
headers = {'content-type''application/json'}
  
ret = requests.post(url, data=json.dumps(payload), headers=headers)
  
print ret.text
print ret.cookies

 

 向https://api.github.com/some/endpoint发送一个POST请求,将请求和相应相关的内容封装在 ret 对象中。

3、其他请求

 

1
2
3
4
5
6
7
8
9
10
requests.get(url, params=None, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)
requests.head(url, **kwargs)
requests.delete(url, **kwargs)
requests.patch(url, data=None, **kwargs)
requests.options(url, **kwargs)
  
# 以上方法均是在此方法的基础上构建
requests.request(method, url, **kwargs)

 

 requests模块已经将常用的Http请求方法为用户封装完成,用户直接调用其提供的相应方法即可,其中方法的所有参数有:

 DELETE 请求

payload = {'some':'data'}
headers = {'content-type': 'application/json'}
url = "https://www.toggl.com/api/v6/" + data_description + ".json"
response = requests.delete(url, data=json.dumps(payload), headers=headers,auth=HTTPBasicAuth(toggl_token, 'api_token'))

  

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.

    :param method: method for the new :class:`Request` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How long to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) <timeouts>` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'http://httpbin.org/get')
      <Response [200]>
    """

    # By using the 'with' statement we are sure the session is closed, thus we
    # avoid leaving sockets open which can trigger a ResourceWarning in some
    # cases, and look like a memory leak in others.
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)
更多参数

 

更多requests模块相关的文档见:http://cn.python-requests.org/zh_CN/latest/

Scrapy

Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中。
其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。Scrapy用途广泛,可以用于数据挖掘、监测和自动化测试。

Scrapy 使用了 Twisted异步网络库来处理网络通讯。整体架构大致如下

Scrapy主要包括了以下组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
引擎(Scrapy)
用来处理整个系统的数据流处理, 触发事务(框架核心)
调度器(Scheduler)
用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可以想像成一个URL(抓取网页的网址或者说是链接)的优先队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址
下载器(Downloader)
用于下载网页内容, 并将网页内容返回给蜘蛛(Scrapy下载器是建立在twisted这个高效的异步模型上的)
爬虫(Spiders)
爬虫是主要干活的, 用于从特定的网页中提取自己需要的信息, 即所谓的实体(Item)。用户也可以从中提取出链接,让Scrapy继续抓取下一个页面
项目管道(Pipeline)
负责处理爬虫从网页中抽取的实体,主要的功能是持久化实体、验证实体的有效性、清除不需要的信息。当页面被爬虫解析后,将被发送到项目管道,并经过几个特定的次序处理数据。
下载器中间件(Downloader Middlewares)
位于Scrapy引擎和下载器之间的框架,主要是处理Scrapy引擎与下载器之间的请求及响应。
爬虫中间件(Spider Middlewares)
介于Scrapy引擎和爬虫之间的框架,主要工作是处理蜘蛛的响应输入和请求输出。
调度中间件(Scheduler Middewares)
介于Scrapy引擎和调度之间的中间件,从Scrapy引擎发送到调度的请求和响应。

 Scrapy运行流程大概如下:

1
2
3
4
5
6
引擎从调度器中取出一个链接(URL)用于接下来的抓取
引擎把URL封装成一个请求(Request)传给下载器
下载器把资源下载下来,并封装成应答包(Response)
爬虫解析Response
解析出实体(Item),则交给实体管道进行进一步的处理
解析出的是链接(URL),则把URL交给调度器等待抓取

 一、安装Scrapy

参考博客---》爬虫的框架安装 

基本使用的 地址 scrapy介绍

二、基本使用

1、创建项目

运行命令:

1
scrapy startproject your_project_name

 创建目录

文件说明:

1
2
3
4
5
scrapy.cfg  项目的配置信息,主要为Scrapy命令行工具提供一个基础的配置信息。(真正爬虫相关的配置信息在settings.py文件中)
items.py    设置数据存储模板,用于结构化数据,如:Django的Model
pipelines    数据处理行为,如:一般结构化的数据持久化
settings.py 配置文件,如:递归的层数、并发数,延迟下载等
spiders      爬虫目录,如:创建文件,编写爬虫规则

 注意:一般创建爬虫文件时,以网站域名命名

2、编写爬虫

在spiders目录中新建 xiaohuar_spider.py 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import scrapy
  
class XiaoHuarSpider(scrapy.spiders.Spider):
    name = "xiaohuar"
    allowed_domains = ["xiaohuar.com"]
    start_urls = [
        "http://www.xiaohuar.com/hua/",
    ]
  
    def parse(self, response):
        # print(response, type(response))
        # from scrapy.http.response.html import HtmlResponse
        # print(response.body_as_unicode())
  
        current_url = response.url
        body = response.body
        unicode_body = response.body_as_unicode()  #def parse(self, response):    #filename = response.url.split('/')[-2] + ".html"    #with open (filename, 'wb') as ft:        #ft.write(response.body)

 3、运行

进入project_name目录,运行命令

1
scrapy crawl spider_name --nolog    就是class下面name等于什么这里spider_name 就是什么

 

***********************************************************************************************

 

ok这样就可以了,但是这样真的可以了吗,不行,为什么,因为太丑了按照开篇图的的逻辑来看

所以我们需要在items里面写规则

那么这种正则还可以怎么写呢?

补充:注:前面的第一个//代表当前的目录的div,那么/代表根目录下的,这里需要注意

案例,校花网里面一个网页的案例,没有用到items

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# from  tutorial.items import TutorialItem
import scrapy
import urllib
 
class XiaoHuarSpider(scrapy.Spider):
    name = "xiaohua"
    # allowed_domains = ["www.xiaohuar.com"]
    start_urls = [
        "http://www.xiaohuar.com/mm/",
    ]
 
    def parse(self, response):
        # print 1
        #这种方式是下载body
        # filename = response.url.split('/')[-2] + ".html"
        # with open (filename, 'wb') as ft:
        #     ft.write(response.body)
        # lis = response.xpath("")
        # for li in lis:
        #     pass
 
        from  scrapy.selector import HtmlXPathSelector
        # print response.body
        hxs = HtmlXPathSelector(response)
        #这么写的目的是因为需要有一个class就是class=container下面的目录是js生成的,所以的这么找
        items = hxs.select('//div[@class="g-mn"]/div[@class="container"]/div[1]/div')
 
        # print items
        for in range(len(items)):
            src = hxs.select(
                '//div[@class="g-mn"]/div[@class="container"]/div[1]/div[%d]/a/img/@src' % i).extract()
 
            school = hxs.select(
                '//div[@class="g-mn"]/div[@class="container"]/div[1]/div[%d]/p/a/text()' % i).extract()
 
            if src and school:
 
                # print src[0],school[0] #因为是列表,所以取值需要索引
                ab_src = "http://www.xiaohuar.com" + src[0]
                file_name = "%s.jpg" % (school[0])
                import os
                file_path = os.path.join("C:\Users\lan\Desktop\lalal",file_name)
                urllib.urlretrieve(ab_src,file_path) #这句是下载的关键

注:可以修改settings.py 中的配置文件,以此来指定“递归”的层数,如: DEPTH_LIMIT = 1

那么这个是一个网页的,但我要是想得到整个网站的呢怎么办?

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import scrapy
from scrapy.http import Request
from scrapy.selector import HtmlXPathSelector
import re
import urllib
import os
 
 
class XiaoHuarSpider(scrapy.spiders.Spider):
    name = "xiaohuar"
    allowed_domains = ["xiaohuar.com"]
    start_urls = [
        "http://www.xiaohuar.com/list-1-1.html",
    ]
 
    def parse(self, response):
        # 分析页面
        # 找到页面中符合规则的内容(校花图片),保存
        # 找到所有的a标签,再访问其他a标签,一层一层的搞下去
 
        hxs = HtmlXPathSelector(response)
 
        # 如果url是 http://www.xiaohuar.com/list-1-\d+.html
        if re.match('http://www.xiaohuar.com/list-1-\d+.html', response.url):
            items = hxs.select('//div[@class="item_list infinite_scroll"]/div')
            for i in range(len(items)):
                src = hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/a/img/@src' % i).extract()
                name = hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/span/text()' % i).extract()
                school = hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/div[@class="btns"]/a/text()' % i).extract()
                if src:
                    ab_src = "http://www.xiaohuar.com" + src[0]
                    file_name = "%s_%s.jpg" % (school[0].encode('utf-8'), name[0].encode('utf-8'))
                    file_path = os.path.join("/Users/wupeiqi/PycharmProjects/beauty/pic", file_name)
                    urllib.urlretrieve(ab_src, file_path)
 
        # 获取所有的url,继续访问,并在其中寻找相同的url
        all_urls = hxs.select('//a/@href').extract()
        for url in all_urls:
            if url.startswith('http://www.xiaohuar.com/list-1-'):
                yield Request(url, callback=self.parse)
参考最下面的这个
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
html = """<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <li class="item-"><a href="link.html">first item</a></li>
    <li class="item-0"><a href="link1.html">first item</a></li>
    <li class="item-1"><a href="link2.html">second item</a></li>
</body>
</html>
"""
response = HtmlResponse(url='http://example.com', body=html,encoding='utf-8')
ret = Selector(response=response).xpath('//li[re:test(@class, "item-\d*")]//@href').extract()
print(ret)
正则选择器
def parse(self, response):
    from scrapy.http.cookies import CookieJar
    cookieJar = CookieJar()
    cookieJar.extract_cookies(response, response.request)
    print(cookieJar._cookies)
获取响应cookie

更多选择器规则:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/selectors.html

 

posted @ 2016-11-03 12:36  众里寻,阑珊处  阅读(256)  评论(0编辑  收藏  举报
返回顶部