检测条目是否存在锚点

时间:2022-09-26 07:47:26

Im trying to display "No website" if there is not a website link available. My code is below. It runs but will not display "No Website".

如果没有可用的网站链接,我试图显示“没有网站”。我的代码如下。它运行但不会显示“没有网站”。

links = page.css("a.track-visit-website")

links.each do |link|
    if links == nil
        puts "no website"

    else
        puts "#{link['href']}"
    end
end

New to Nokogiri, what am I doing wrong here.

Nokogiri的新手,我在这里做错了什么。

Here is script if you would like to replicate.

如果您想要复制,这是脚本。

require 'rubygems'
require 'nokogiri'
require 'open-uri'

page = Nokogiri::HTML(open("http://www.yellowpages.com/austin-tx/screen-printing?g=Austin%2C+TX&q=screen+printing"))


links = page.css("a.track-visit-website")



links.each do |link|
    if links == nil?
        puts "no website"

    else
        puts "#{link['href']}"
    end
end

2 个解决方案

#1


2  

You need to find an element that represents the result or company. Only from there can you determine if that company has a website or not.

您需要找到代表结果或公司的元素。只有从那里你可以确定该公司是否有网站。

Assuming you only care about the companies listed in the actual search results, the following will iterate through the companies and get their website if available or output no website:

假设您只关心实际搜索结果中列出的公司,以下内容将遍历公司并获取其网站(如果可用)或不输出任何网站:

require 'nokogiri'
require 'open-uri'

page = Nokogiri::HTML(open("http://www.yellowpages.com/austin-tx/screen-printing?g=Austin%2C+TX&q=screen+printing"))

companies = page.css('#results div.result')
companies.each do |company|
    website_link = company.at_css("a.track-visit-website")
    if website_link
        puts website_link['href']
    else
        puts 'no website'
    end
end

#2


1  

You are testing the whole of the links array for nil rather than the individual element. Try doing

您正在测试整个链接数组的nil而不是单个元素。试着做

if link.nil?
  puts "No Website"
else
  ....

#1


2  

You need to find an element that represents the result or company. Only from there can you determine if that company has a website or not.

您需要找到代表结果或公司的元素。只有从那里你可以确定该公司是否有网站。

Assuming you only care about the companies listed in the actual search results, the following will iterate through the companies and get their website if available or output no website:

假设您只关心实际搜索结果中列出的公司,以下内容将遍历公司并获取其网站(如果可用)或不输出任何网站:

require 'nokogiri'
require 'open-uri'

page = Nokogiri::HTML(open("http://www.yellowpages.com/austin-tx/screen-printing?g=Austin%2C+TX&q=screen+printing"))

companies = page.css('#results div.result')
companies.each do |company|
    website_link = company.at_css("a.track-visit-website")
    if website_link
        puts website_link['href']
    else
        puts 'no website'
    end
end

#2


1  

You are testing the whole of the links array for nil rather than the individual element. Try doing

您正在测试整个链接数组的nil而不是单个元素。试着做

if link.nil?
  puts "No Website"
else
  ....