将文档中的特定行.txt添加到具有特定 ID 的注释字段,然后移动到下一行?



如何将文档中的特定行.txt添加到具有特定ID的YouTube评论字段中,然后移动到文档的下一行.txt。YouTube评论字段的ID是"contenteditable-root"。我已经创建了此代码,但是在YouTube评论字段中添加的文本显示在括号中,例如["Hello"]

或者在第二个示例中,它什么也没显示

示例 1:

file = 'comments.txt'
File.readlines(file).each do |i|
files = [i]
files.each { |val| 
browser.execute_script("document.getElementById('contenteditable-root').innerHTML = '#{files}';")
}
end

示例 2:

line_number = 1 
loop do
comments = IO.readlines('comments.txt')[line_number-1]
browser.execute_script("document.getElementById('contenteditable-root').innerHTML = '#{comments}';")
line_number += 1 
end

注释.txt文件:

Hellooo !!
hi
Goodbye 
Goodnight 

假设这里的一大堆其他事情是正确的,你正在做一个非常奇怪的迭代,你应该只使用:

file = 'comments.txt'
File.readlines(file).each do |i|
browser.execute_script("document.getElementById('contenteditable-root').innerHTML = '#{i}';")
end

在我看来,你需要学习如何调试。

第 1 步:如果您的代码打印了正确的文本,请检查irb(关于 irb(:

File.readlines('comments.txt').each do |line|
p line
end

预期产出:

=> "Line 1"
=> "Line 2"
=> "Line 3"

如果没有,则查找如何读取每行的文件。

第 2 步:你的 Javascript 真的有效吗?

转到您尝试测试的页面,打开调试器 (F12( 并直接从控制台运行 Javascript:

document.getElementById('contenteditable-root').innerHTML = 'hi';

如果它不起作用,那么尝试学习更多关于Javascript如何与元素交互的信息。

第 3 步:我的代码段实际上可以在 Watir 中使用吗?

再次打开irb并尝试一下

require 'watir'
b = Watir::Browser.new
b.goto 'https://youryoutubepage.com/path'
b.execute_script("document.getElementById('contenteditable-root').innerHTML = 'hi';")

如果失败,请谷歌错误,查找瓦蒂尔并execute_script。

然后最后在irb中运行代码的整个组合:

require 'watir'
b = Watir::Browser.new
b.goto 'https://youryoutubepage.com/path'
File.readlines('comments.txt').each do |line|
b.execute_script("document.getElementById('contenteditable-root').innerHTML = 'hi';")
sleep 5 # Give yourself some time to visually confirm the changes.
end

快速谷歌一下你的SyntaxError: Invalid or unexpected token (Selenium::WebDriver::Error::UnknownError)我看到这可能是execute_script不喜欢的报价的问题。

也许尝试反转引号:

b.execute_script('document.getElementById("contenteditable-root").innerHTML = "hi";')

将来,请尝试查明您的问题,不要使用 StackOverflow 作为调试代码的地方。让您的代码逐步工作,并将您的问题集中在未按预期工作的特定函数上。

最新更新