【问题标题】:Selenium : Click on a link inside a divSelenium :单击 div 内的链接
【发布时间】:2020-06-02 04:23:14
【问题描述】:

我正在学习 selenium,我正在尝试一个简单的事情:点击 wikipedia 上搜索的第一个结果。

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

PATH = "chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://en.wikipedia.org")

# Input in the search bar
search = driver.find_element_by_id("searchInput")
search.send_keys("python", Keys.RETURN)


wait = WebDriverWait(driver, 10)
first_result = wait.until(
    EC.presence_of_element_located((By.CLASS_NAME, "mw-search-result-heading"))
)

first_result.click()

所以我可以选择第一个结果的标题。但我无法点击它。 我认为这是因为我点击了包含链接的<div>,而不是实际的链接。这是 HTML 的 sn-p :

如何定位实际的 <a> 链接,而它没有任何类名、id 或名称?

【问题讨论】:

  • presence_of_element_located 没有 return 元素 - 它只是 returnstrue` 或 false - 也就是说,找到与否。 find_element_by_... 方法可用于return 元素。
  • @Haezer 您要定位哪个元素By.CLASS_NAME, "mw-search-result-heading"

标签: python selenium web-scraping


【解决方案1】:

您可以链接 find_* 函数以更具体地处理您的 WebElement 查询:

first_result.find_element_by_tag_name("a").click()

【讨论】:

    【解决方案2】:

    由于您使用的是 Selenium,您可能希望使用 XPath。这为我节省了很多次!只需右键单击所需的标签,然后单击复制 xpath。 然后只需使用与此处类似的语法单击对象:

    elem = driver.find_element_by_xpath('//some_xpath')
    elem.click()
    

    【讨论】:

    • 感谢您的提示,相信它在未来会很有帮助!它没有回答最初的问题,因为每次搜索的链接的 xpath 似乎都不同。
    【解决方案3】:

    点击链接Python (langage) 诱导WebDriverWait() 并等待element_to_be_clickable() 并使用css selectorxpathlink_text

    CSS 选择器:

    driver.get("https://en.wikipedia.org")
    WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
    first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[title='Python (langage)']")))
    first_result.click()
    

    Xpath:

    driver.get("https://en.wikipedia.org")
    WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
    first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, "//a[@title='Python (langage)']")))
    first_result.click()
    

    LINK_TEXT:

    driver.get("https://en.wikipedia.org")
    WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"searchInput"))).send_keys("python", Keys.RETURN)
    first_result = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Python (langage)")))
    first_result.click()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多