0

我在 Service Now 网站上使用 Selenium 和 Python3。

所以过程如下: selenium 加载 ServiceNow URL,然后我使用 sendKeys 自动输入用户名和密码,然后加载包含我需要提取的事件表的页面。不幸的是,由于我拥有的组策略,我每次都必须登录。

这一直有效,直到我必须找到带有数据的动态呈现的 Javascript 表,而我似乎一辈子都找不到它。我什至尝试在那里休眠 15 秒以使其加载。

我还仔细检查了 XPath 和 Id / 类名称,它们匹配。当我打印 query.page_source 时,我看不到 JS 呈现的任何内容。

我也用过漂亮的汤,但这也行不通。

有任何想法吗?

from time import sleep
from collections import deque
from selenium import webdriver
from selenium.webdriver.support.ui import Select # for <SELECT> HTML form
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

query = webdriver.Firefox()

get_query = query.get("SERVICENOW URL")

query.implicitly_wait(10)

login_username = query.find_element_by_id('username')

login_password = query.find_element_by_id('password')

login_button = query.find_element_by_id('signOnButton')

username = "myUsername"
password = "myPassword"

login_username.send_keys(username)
login_password.send_keys(password)
login_button.click()

sleep(10)

incidentTableData = []

print(query.page_source)

// *** THESE ALL FAIL AND RETURN NONE ***
print(query.find_elements())
tableById = query.find_element_by_id('service-now-table-id')
tableByXPath = query.find_element_by_xpath('service-now-xpath')
tableByClass = query.find_element_by_id('service-now-table-class')
4

1 回答 1

0

由于它是dynamically rendered Javascript table,我建议您在代码中实现显式等待。

所以而不是这个:

tableById = query.find_element_by_id('service-now-table-id')
tableByXPath = query.find_element_by_xpath('service-now-xpath')
tableByClass = query.find_element_by_id('service-now-table-class')

像这样重写这些行:

wait = WebDriverWait(query, 10)
service_now_with_id = wait.until(EC.element_to_be_clickable((By.ID, "service-now-table-id")))
service_now_with_xpath = wait.until(EC.element_to_be_clickable((By.XPATH, "service-now-xpath")))
service_now_with_class = wait.until(EC.element_to_be_clickable((By.ID, "service-now-table-class")))

您将需要使用以下导入

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as E

PS :- service_now_with_id, service_now_with_xpath, service_now_with_class, 这些是显式等待返回的 Web 元素。您可能需要根据您的要求含义与它们进行交互,单击它或发送密钥或其他任何方式。

于 2021-07-13T03:52:39.850 回答