如何避免重复条目爬网网站
How to avoid duplicate entries crawling a site
我想用 Ruby、Nokogiri 和 Mechanize 抓取一家商店。
在显示两篇文章的页面上,我知道所有文章的地址都以 .../p/...
开头,所以我将其存储在 article_links
中。应显示所有 /p/
link。
通常我会看到两个地址:
agent = Mechanize.new
page = agent.get(exampleshop.com)
article_links = page.links_with(href: %r{.*/p/})
article_links.map do |link|
article = link.click
target_URL = page.uri + link.uri #full URL
puts "#{target_URL}"
end
#crawling stuff on /p/ pages not included here
然而,最后每个 link 都是重复的,这已经发生在循环之前,所以我看到:
exampleshop.com/p/productxy.html
exampleshop.com/p/productxy.html
exampleshop.com/p/productab.html
exampleshop.com/p/productab.html
我相信站点代码中的每个产品都有两个带有 /p/
的 href。有什么好的方法可以防止这种情况发生吗?或者是否可以在 links_with
中使用 Nokogiri CSS?
您可以在遍历列表之前删除重复项:
而不是
article_links.map do |link|
写入
article.links.uniq { |link| link.uri }.map do |link|
这将删除任何具有重复 uri 的链接。
您可以使用 CSS regex selectors 而不是 links_with
,但您仍然需要删除 Ruby 中的重复项:
article_links = page.css("a[href*='/p/']")
您仍然需要删除 Ruby 中的重复项的原因是 CSS 无法 select 匹配的第一个元素。 nth-of-type or nth-child 在这里不起作用。
我想用 Ruby、Nokogiri 和 Mechanize 抓取一家商店。
在显示两篇文章的页面上,我知道所有文章的地址都以 .../p/...
开头,所以我将其存储在 article_links
中。应显示所有 /p/
link。
通常我会看到两个地址:
agent = Mechanize.new
page = agent.get(exampleshop.com)
article_links = page.links_with(href: %r{.*/p/})
article_links.map do |link|
article = link.click
target_URL = page.uri + link.uri #full URL
puts "#{target_URL}"
end
#crawling stuff on /p/ pages not included here
然而,最后每个 link 都是重复的,这已经发生在循环之前,所以我看到:
exampleshop.com/p/productxy.html
exampleshop.com/p/productxy.html
exampleshop.com/p/productab.html
exampleshop.com/p/productab.html
我相信站点代码中的每个产品都有两个带有 /p/
的 href。有什么好的方法可以防止这种情况发生吗?或者是否可以在 links_with
中使用 Nokogiri CSS?
您可以在遍历列表之前删除重复项:
而不是
article_links.map do |link|
写入
article.links.uniq { |link| link.uri }.map do |link|
这将删除任何具有重复 uri 的链接。
您可以使用 CSS regex selectors 而不是 links_with
,但您仍然需要删除 Ruby 中的重复项:
article_links = page.css("a[href*='/p/']")
您仍然需要删除 Ruby 中的重复项的原因是 CSS 无法 select 匹配的第一个元素。 nth-of-type or nth-child 在这里不起作用。