Php 文件读取并以多对一关系将其放入循环中

Php 文件读取并以多对一关系将其放入循环中,php,ruby,web-scraping,nokogiri,watir-webdriver,Php,Ruby,Web Scraping,Nokogiri,Watir Webdriver,我试图在读取文本文件后在watir方法中分配一个变量。我使用以下方法。在循环中,第一个循环工作正常,但在第二个循环中显示错误 我的代码如下: file = File.new("states.txt", "r") contentsArray=[] # start with an empty array file.each_line {|line| contentsArray.push line } browser = Watir::Browser.new browser.goto 'http

我试图在读取文本文件后在watir方法中分配一个变量。我使用以下方法。在循环中,第一个循环工作正常,但在第二个循环中显示错误

我的代码如下:

file = File.new("states.txt", "r")
contentsArray=[]  # start with an empty array
file.each_line {|line|
 contentsArray.push line
}

browser = Watir::Browser.new
browser.goto 'http://example.com'

for y in 0..2 do
puts state=contentsArray[y]
browser.text_field(:name => 'Keyword').set 'Pediatrics'
browser.text_field(:name => 'Address').set "#{state}"
browser.div(:id => 'uniform-formSearchDoctorBtn').fire_event :click

browser.link(:class => "start-over pull-right gen-button").click
 end
发生以下错误

`assert_exists': unable to locate element, using {:id=>"uniform-formSearchDoctorBtn", :tag_name=>"div"} (Watir::Exception::UnknownObjectException)
当我放置一个静态数组代替
contentsArray

contentsArray=Array['AL','AK','AZ','AR']

然后代码工作正常。

是的,在justin的帮助下得到了解决方案。 如果您输出contentsArray,您可能会得到

["AL\n", "AK\n", "AZ\n", "AR"]
请注意,有一个“\n”,它是换行符。您想通过更改contentsArray.push line来删除换行符

contentsArray.push line.strip

有关更多详细信息,请参阅问题“如何使用Ruby删除回车?”贾斯汀·柯(Justin Ko)

这个问题相当广泛,很难回答。例如,您是否在读取文件或创建不同的组合时遇到问题?如果您在读取文件时遇到问题,它是什么类型的文件(例如Excel、csv等)。请考虑更新这个问题来显示你所尝试的和你在哪里。嗨,贾斯廷,我已经编辑了这个问题。如果你输出<代码>内容数组>代码>,你可能会得到<代码> [“al\n”,“Ak\n”,“AZ\n”,“Ar”)< /C>。请注意,有一个“\n”,它是换行符。通过将
contentsArray.push-line
更改为
contentsArray.push-line.strip,可以
strip
换行符。更多细节,请看问题谢谢你,贾斯汀。现在开始工作了。