首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby Anemone爬行器为访问的每个url添加一个标签

Ruby Anemone爬行器为访问的每个url添加一个标签
EN

Stack Overflow用户
提问于 2011-09-08 18:56:05
回答 1查看 1.4K关注 0票数 3

我设置了一个爬网:

代码语言:javascript
复制
require 'anemone'

Anemone.crawl("http://www.website.co.uk", :depth_limit => 1) do |anemone|
anemone.on_every_page do |page|
  puts page.url
end
end

然而,我希望蜘蛛在它访问的每个URL上都使用谷歌分析反跟踪标签,而不一定真的点击链接。

我可以使用爬行器一次,存储所有的网址,并使用WATIR遍历它们,添加标记,但我希望避免这样做,因为它很慢,而且我喜欢skip_links_like和页面深度函数。

我怎么才能实现它呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-09 01:02:59

在加载之前,您想要向URL添加一些内容,对吗?为此,您可以使用focus_crawl

代码语言:javascript
复制
Anemone.crawl("http://www.website.co.uk", :depth_limit => 1) do |anemone|
    anemone.focus_crawl do |page|
        page.links.map do |url|
            # url will be a URI (probably URI::HTTP) so adjust
            # url.query as needed here and then return url from
            # the block.
            url
        end
    end
    anemone.on_every_page do |page|
        puts page.url
    end
end

用于过滤URL列表的focus_crawl方法:

指定一个区块,该区块将选择每个页面上要遵循的链接。该块应返回一个URI对象数组。

但您也可以将其用作通用URL过滤器。

例如,如果您想将atm_source=SiteCon&atm_medium=Mycampaign添加到所有链接,那么您的page.links.map将如下所示:

代码语言:javascript
复制
page.links.map do |uri|
    # Grab the query string, break it into components, throw out
    # any existing atm_source or atm_medium components. The to_s
    # does nothing if there is a query string but turns a nil into
    # an empty string to avoid some conditional logic.
    q = uri.query.to_s.split('&').reject { |x| x =~ /^atm_(source|medium)=/ }

    # Add the atm_source and atm_medium that you want.
    q << 'atm_source=SiteCon' << 'atm_medium=Mycampaign'

    # Rebuild the query string 
    uri.query = q.join('&')

    # And return the updated URI from the block
    uri
end

如果您atm_sourceatm_medium包含非URL安全字符,则对它们进行URI编码。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7346933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档