【发布时间】:2021-05-11 07:08:14
【问题描述】:
我正在尝试使用 Selenium WebDriver 在 Python 文件中运行 javascript 文件并从 javascript 函数中获取返回值。下面的尝试应该可以从我在网上查到的内容进行。我已经为此工作了几个小时,但无济于事。任何帮助将不胜感激。
Python 代码:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import os
driver = webdriver.Chrome(executable_path='chromedriver')
driver.get('example.com')
# Clean up the text inside the <p> tags
js_file = 'clean_text.js'
with open(js_file, 'r') as f:
script = f.read()
# Attempt 1
text = driver.execute_script(script)
# Attempt 2
text = driver.execute_script(f'return {script}')
# Attempt 3
text = WebDriverWait(driver, 20).until(lambda driver: driver.execute_script(script))
# Attempt 4
text = WebDriverWait(driver, 20).until(lambda driver: driver.execute_script(f'return {script}'))
尝试返回 None 或 selenium.common.exceptions.TimeoutException
Javascript 代码:
$(document).ready(function() {
// Collect the text within the nested <p> tags
var text = [];
// get all nested <p> tags
let paragraphs = $(`div#id div[data-test-id=value] p`);
// Replace all whitespaces with a single white space
paragraphs.each(function(index) {
let original_text = $(this).text();
let cleaned_text = original_text.trim().replace(/\s\s+/g, ' ');
$(this).text(cleaned_text);
text.push(cleaned_text);
});
return text;
});
鉴于此 JS 代码下方的 furas 答案适用于尝试 1 和 4。我需要在开头添加“return”,“();”最后并删除 jQuery。
return function cleanText() {
// Collect the text within the nested <p> tags
var text = [];
// get all nested <p> tags
let paragraphs = $(`div#id div[data-test-id=value] p`);
// Replace all whitespaces with a single white space
paragraphs.each(function(index) {
let original_text = $(this).text();
let cleaned_text = original_text.trim().replace(/\s\s+/g, ' ');
$(this).text(cleaned_text);
text.push(cleaned_text);
});
return text;
}();
【问题讨论】:
-
您是否在代码中加载了
jQuery?你不能在没有jQuery的情况下使用$(...)。 -
首先您可以在 javaScript 中使用
console.log(...)在 Web 浏览器的 DevTools 中的 JavaScript 控制台中显示信息。通过这种方式,您可以检查(在 JavaScript 中)变量中的内容以及执行的代码部分。 -
jQuery 已经加载到脚本中。我添加了一个警报(文本);返回文本的正上方;我回去添加了一个 conosle.log(...);这两个都有效。 Selenium 仍在接收无。
-
我认为您以错误的方式使用
jQuery-function()在ready()内部执行,因此return将text发送给ready(),而不是发送给您。你应该直接运行function()来得到它的结果。
标签: javascript python selenium