online panel在广告曝光日志中的特征进一步提取

Scrapy解析url视频基本信息(不爬取)

    好久没写过博客了,近来感觉还是有必要mark下工作的内容。从今天开始吧。
    现手上有一批广告曝光日志,与online panel(在线样本库)(交集的量还是很大的)。由于online panel的用户标识id很少,因此想基于现有的panel,从曝光日志中获取一部分特征,来构建个分类器,以期评判那些不在online panel的用户的ta(target audience)属性。
    然而,现有的数据携带的特征较少,只有用户行为的ip、访问url、来源url、点击或者曝光等。基于现有特征的分类器的预测ta类别效果不佳。因此想到,通过用户访问的url,去对应网站获得一些基本信息来强化特征。本文就是基于这种背景去调研的。
    提供url解析的工具不少,例如htmlpaser、beatiful soup、lxml等。但为了以后业务的拓展(可能进行视频基本信息爬取),最终采用了scrapy。
    scrapy是一个开源爬虫框架。这里不在赘述具体的介绍和使用,有需要的还是老老实实去看官方文档吧。不是很难,很快就能上手。
    事实上,我这个任务不涉及到爬取功能,主要操作是爬虫的start_urls,因为我们已经有url了,只做这些url的基本信息解析。
    手上的广告曝光日志主要是一些视频网站的url,有用的特征很多,但容易提取出来的特征主要就是视频标题,视频标签?,视频类别以及描述。
    理解scrapy后,实现挺简单的,先贴出解析youku的视频(仅限于v.youku.com)的代码实现吧。
    首先是items.py:

import scrapy
from scrapy.item import Item,Field

class YoukuItem(Item):
    url = Field()
    title = Field()
    crumbs  = Field()
    description = Field()
    tags = Field()

    然后是piplelines.py:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import MySQLdb
import MySQLdb.cursors
from twisted.enterprise import adbapi
from scrapy import log

class YoukuPipeline(object):
    def __init__(self):
        self.dbpool = adbapi.ConnectionPool('MySQLdb',
                db = 'medias',
                user = 'root',
                passwd = 'root',
                cursorclass = MySQLdb.cursors.DictCursor,
                charset = 'utf8',
                use_unicode = True
        )

    def process_item(self, item, spider):
        if spider.name in ['youkucrawl']:
            query = self.dbpool.runInteraction(self._conditional_insert, item)
            query.addErrback(self.handle_error)
        else:
            print item
        return item

    def _conditional_insert(self, tx, item):
        if item.get('url'):
            tx.execute('replace into youku values (%s, %s, %s, %s, %s)', (item['url'], item['title'], item['crumbs'], item['description'], item['tags']))

    def handle_error(self, e):
        log.err(e)

     最后是spider的实现:

#!/usr/bin/env python
#coding=utf8

import scrapy, os
import traceback
from scrapy.spider import Spider

from myspider.items import YoukuItem

class YoukuSpider(Spider):
    def __init__(self, url = None, *args, **kwargs):
        super(YoukuSpider, self).__init__(*args, **kwargs)
        if url != None:
            self.start_urls = [url]
        else:
            youkufilename = 'youku.txt'
            if os.path.exists(youkufilename):
                youkudata = open(youkufilename,'r')
                while 1:
                    lines = youkudata.readlines(100000)
                    if not lines:
                        break
                    for line in lines:
                        line = line.strip()
                        if line.startswith("http://v.youku.com"):
                           self.start_urls.append(line)

    #start_urls = ["http://v.youku.com/v_show/id_XOTIyNjkwODk2.html?ev=1&from=y1.1-2.10001-0.1-1"]
    allowed_domains = ["v.youku.com"]
    name = 'youkucrawl'
    def parse(self, response):
        try:
            self.log('%s comes in!' % response.url)
            item = YoukuItem()
            item['url'] = response.url
            item['title'] = ','.join(response.xpath('//h1[@class="title"]').xpath('string(.)').extract()).replace('\n','').replace('\t',' ').strip()
            item['crumbs'] = ",".join(response.xpath('//div[@class="crumbs"]').xpath('string(.)').extract()).replace('\n','').replace('\t',' ').strip()
            item['tags'] = ','.join(response.xpath('//span[@class="tag"]').xpath('string(.)').extract()).replace('\n','').replace('\t',' ').strip()
            item['description'] = ','.join(response.css('meta[name="description"]::attr(content)').extract()).replace('\n','').replace('\t',' ').strip()
            print response.url + ':' + item['title'].encode('utf8')
            return item
        except Exception,e:
            print traceback.format_exc()

    这里是配置文件:

# -*- coding: utf-8 -*-

# Scrapy settings for myspider project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
#     http://doc.scrapy.org/en/latest/topics/settings.html
#

BOT_NAME = 'myspider'

SPIDER_MODULES = ['myspider.spiders']
NEWSPIDER_MODULE = 'myspider.spiders'

ITEM_PIPELINES = {'myspider.pipelines.YoukuPipeline':1000,}

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'myspider (+http://www.yourdomain.com)'

    这里仅提供了一个简单的版本,实现对youku的视频基本信息获取,事实上可以做一个更简单的通用版本,仅获得视频title、keywords和description,从html的meta中获得。
    该程序可通过以下命令测试单个url的结果:

scrapy crawl youkucrawl -a url=http://v.youku.com/v_show/id_XOTI0MjI2MDY0.html?f=23465260&ev=1

    批量处理可在项目主目录下新建个youku.txt测试结果,生成结果存取在mysql中。运行命令为:

scrapy crawl youkucrawl


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值