gpt4 book ai didi

nokogiri - 找不到结果时屏幕抓取?

转载 作者:行者123 更新时间:2023-12-04 16:20:52 25 4
gpt4 key购买 nike

我在屏幕抓取 rake 任务中有以下代码

page = agent.get("https://domainname.co.uk/unit/27/logs?type=incoming&page=8")
page = agent.page.search("table tbody tr").each do |row|
next if (!row.at('td'))
time, source, destination, duration = row.search('td')[1..5].map{ |td| td.text.strip }
parsed_time = Time.parse(time)
unless Call.find_by_time(parsed_time)
Call.create({:time => parsed_time, :source => source, :destination => destination, :duration => duration})
end
end

脚本的这一部分导航到第 8 页,然后为每个表格数据行创建一个调用记录。

如果我导航到的页面不包含任何通话记录,它会显示以下代码:
<tr class='no-data'>
<td colspan='7'>There are no call records matching the search criteria</td>
</tr>

当 rake 任务导航到没有调用日志的页面时,任务无法完成。它显示以下错误:
rake aborted!
can't convert nil into String

那么,在使用 Nokogiri 和 Mechanize 时有没有办法从 nil 中恢复?是否有一种简单的方法来检查 <tr class='no-data'>在尝试导入数据之前存在吗?

使用建议代码更新

错误信息
Scraping Page 9
rake aborted!
can't convert nil into String

代码
puts 'Scraping Page 9'    
if agent.page.root.css('tr.no-data').empty?
page = agent.get("https://domaindname.co.uk/27/logs?type=incoming&page=9")
page = agent.page.search("table tbody tr").each do |row|
next if (!row.at('td'))
time, source, destination, duration = row.search('td')[1..5].map{ |td| td.text.strip }
parsed_time = Time.parse(time)
unless Call.find_by_time(parsed_time)
Call.create({:time => parsed_time, :source => source, :destination => destination, :duration => duration})
end
end
else
puts 'No calls on this page'
end

最佳答案

您可以检查该元素是否存在

if agent.page.root.css('tr.no-data').empty?
# it doesn't exist
else
# do the normal thing
end

关于nokogiri - 找不到结果时屏幕抓取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com