我们如何使用 python 在新页面重新加载后点击链接?

How can we click on the links after new page reload using python?

基本上我想自动化 google 搜索引擎,它基本上搜索并单击第一个 link,它在单击搜索按钮后填充,所以我使用 python 执行此操作。我可以成功搜索内容,但无法在页面重新加载后点击 link

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

url = "https://www.google.com"
driver = webdriver.Chrome("C:/Users/User/Python/AllCodes/chromedriver.exe")

driver.get(url)
insert = driver.find_element_by_name("q")
insert.send_keys("K.J.Somaiya")
button = driver.find_element_by_name("btnK")
button.submit()
# after this new page reload and link are poluated

linktext = driver.find_element_by_link_text("K. J. Somaiya Institute of Management")
linktext.submit()

这个输入 class 我用的名字是 q

<input class="gLFyf gsfi" jsaction="paste:puy29d;" maxlength="2048" name="q" type="text" aria-autocomplete="both" aria-haspopup="false" autocapitalize="off" autocomplete="off" autocorrect="off" autofocus="" role="combobox" spellcheck="false" title="Search" value="" aria-label="Search" data-ved="0ahUKEwj9qOfEmLzvAhWSj-YKHZUYDngQ39UDCAQ">

This the html code from i target linktext which is K.J.Somaiya Inst.....

您需要等到该元素在 dom 中可见。了解硒等待 here

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = "https://www.google.com"
driver = webdriver.Chrome("C:/Users/User/Python/AllCodes/chromedriver.exe")

driver.get(url)
insert = driver.find_element_by_name("q")
insert.send_keys("K.J.Somaiya")
button = driver.find_element_by_name("btnK")
button.submit()
# after this new page reload and link are poluated
linktext = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "K. J. Somaiya"))
    ) # Waits 10 second before element loads.

linktext.click()