我设置了一个爬网:
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和页面深度函数。
我怎么才能实现它呢?
发布于 2011-09-09 01:02:59
在加载之前,您想要向URL添加一些内容,对吗?为此,您可以使用focus_crawl。
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将如下所示:
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_source或atm_medium包含非URL安全字符,则对它们进行URI编码。
https://stackoverflow.com/questions/7346933
复制相似问题