python - 我的脚本无法单击某个网格

标签 python python-3.x selenium selenium-webdriver web-scraping

我用 python 结合 selenium 编写了一个脚本,以从网页中获取一些信息。要到达内容,需要经过几个步骤,如接受条件填写输入框点击搜索按钮进行填充结果,最后单击填充表中的第一个网格(更具体地说,是第一个 tr)。一旦在第一个 tr 上发起任何点击,就会打开一个新页面(包含所需信息)。

我的脚本可以成功完成前三个步骤。我不能做的是:

  1. 在第一个 tr 上执行点击
  2. 聚焦到新打开的选项卡(包含我想要的信息)

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 with HMC 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/

相关文章:

python - 展开时在 sizer 中为 wx.CollapsiblePane 分配更多的大小

python - Python 中的多处理 : Handle Multiple Worker Threads

Python 税收计算器 - 算法无法正常工作

python - Selenium 单击 href 按钮

javascript - 使用 Selenium 测试由 javascript 生成的 html

python - 在 Django 中使用 Pre_delete 信号

python - 在 PyTest 中创建一个临时目录

python - 导入错误: cannot import name 'unicode_csv_reader' from 'torchtext.utils'

python - 如何解码字节对象的字符串表示?

java - 无法使用 selenium webdriver 在撰写电子邮件页面上的“收件人”(电子邮件 ID)字段中发送 key