【问题标题】:How can we click on the links after new page reload using python?使用python重新加载新页面后如何单击链接?
【发布时间】:2021-03-19 11:30:44
【问题描述】:

基本上,我想自动化谷歌搜索引擎,它基本上搜索并单击单击搜索按钮后填充的第一个链接,所以我使用 python 来执行此操作。我可以成功搜索到东西,但页面重新加载后无法点击链接

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()

这个输入类我使用的名字是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.....

【问题讨论】:

  • 添加一些 HTML 代码,然后解释 wat 是您的错误代码问题。你想重新加载并在谷歌搜索页面上还是被转移到你搜索的链接?
  • 你试过linktext.click()而不是linktext.submit()吗?
  • @GajJulije 我已经在图像文件中发布了 html 代码
  • "C:\Users\User\Python\login.py",第 16 行,在 driver.find_elements_by_class_name("LC20lb DKV0Md").click() AttributeError: 'list' object has没有属性“点击”
  • @GajJulije 谢谢,因为这个类是动态变化的,所以我必须要这样一个不会改变的类我明白你的意思

标签: python selenium automation new-operator


【解决方案1】:

您需要等到该元素在 dom 中可见。了解 selenium 等待 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()

【讨论】:

  • # Waits 10 second before element loads. 只是为了清楚一点......它实际上并没有等待 10 秒,它等待 最多 10 秒。它立即检查,如果检查通过,则停止等待,代码继续。如果检查失败,它会每 500 毫秒尝试(轮询)一次,最多 10 秒,直到成功并继续或超时,抛出异常。
猜你喜欢
  • 2014-02-11
  • 2018-08-11
  • 2021-06-14
  • 1970-01-01
  • 2015-06-09
  • 2017-08-21
  • 2020-12-31
  • 1970-01-01
  • 2016-10-28
相关资源
最近更新 更多