读取文件时从十个 URL 中查找所有链接

Finding all links from ten URLs while reading a file

如何在读取文件时从页面中提取 href 标记中的所有 href 选项?

如果我有一个包含目标 URL 的文本文件:

http://mypage.com/1.html
http://mypage.com/2.html
http://mypage.com/3.html
http://mypage.com/4.html

这是我的代码:

File.open("myfile.txt", "r") do |f|
  f.each_line do |line|
    # set the page_url to the current line 
    page = Nokogiri::HTML(open(line))
    links = page.css("a")
    puts links[0]["href"]
  end
end

我会翻转它。我会首先解析文本文件并将每一行加载到内存中(假设它的数据集足够小)。然后为您的 HTML 文档创建一个 Nokogiri 实例并提取所有 href 属性(就像您正在做的那样)。

类似这样的未经测试的代码:

links = []
hrefs = []

File.open("myfile.txt", "r") do |f|
  f.each_line do |line|
    links << line
  end
end


page = Nokogiri::HTML(html)
page.css("a").each do |tag|
  hrefs << tag['href']
end

links.each do |link|
  if hrefs.include?(link)
    puts "its here"
  end
end

如果我只想为每个 <a> 输出 'href',我会这样写:

File.foreach('myfile.txt') do |url|
  page = Nokogiri::HTML(open(url))
  puts page.search('a').map{ |link| link['href'] }
end

当然 <a> 标签不必有 'href' 但 puts 不在乎。