我用 python 结合 selenium 编写了一个脚本,以从网页中获取一些信息。要到达内容,需要经过几个步骤,如接受条件
、填写输入框
、点击搜索按钮
进行填充结果,最后单击填充表中的第一个网格
(更具体地说,是第一个 tr)。一旦在第一个 tr
上发起任何点击,就会打开一个新页面(包含所需信息)。
我的脚本可以成功完成前三个步骤。我不能做的是:
在第一个 tr 上执行点击
聚焦到新打开的选项卡
(包含我想要的信息)
To reach the content:
This is the link to follow. There is an accept button to click first. Then there is an inputbox
Name
to be filled in withHMC DESIGN GROUP
. Now, pressing the search button, the result should appear below within a table. From there I need to click on the first tr.
这是我迄今为止尝试过的:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
link = "https://officialrecords.broward.org/AcclaimWeb/search/SearchTypeName"
def get_information(driver,url):
driver.get(url)
wait.until(EC.element_to_be_clickable((By.ID, "btnButton"))).click()
wait.until(EC.presence_of_element_located((By.ID,"SearchOnName"))).send_keys("HMC DESIGN GROUP")
wait.until(EC.presence_of_element_located((By.ID, "btnSearch"))).click()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,".t-grid-content table tr"))).click()
if __name__ == "__main__":
driver = webdriver.Chrome()
wait = WebDriverWait(driver,10)
try:
get_information(driver,link)
finally:
driver.quit()
当前脚本既不会点击网格新生成的表的第一个tr
也不会抛出任何错误。它会优雅地退出浏览器。
最佳答案
在div
下还有另一个table
,具有相同的类名“t-grid-content”
。它显示为“正在加载...”
。因此,在提交搜索后,您确实使用选择器 ".t-grid-content table tr"
单击了节点,但它只是没有产生适当的效果
您只需要更具体的选择器。
例如,尝试一下
wait.until(EC.element_to_be_clickable((By.XPATH, "//td[contains(., 'HMC DESIGN GROUP')]")))
要切换到新窗口,请尝试将函数体更新为
driver.get(url)
current = driver.current_window_handle
wait.until(EC.element_to_be_clickable((By.ID, "btnButton"))).click()
wait.until(EC.presence_of_element_located((By.ID,"SearchOnName"))).send_keys("HMC DESIGN GROUP")
wait.until(EC.presence_of_element_located((By.ID, "btnSearch"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//td[contains(., 'HMC DESIGN GROUP')]"))).click()
driver.switch_to.window([window for window in driver.window_handles if window != current][0])
关于python - 我的脚本无法单击某个网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346347/