【问题标题】:How to click in a div?如何点击一个div?
【发布时间】:2020-03-16 15:33:21
【问题描述】:

我正在尝试单击不同的 div 类 TopBox。我尝试了下面的代码,但我没有执行点击:

driver.find_element_by_css_selector('#home > div > div.row.topBoxs > div.col-xs-12.col-lg-10 > div > div:nth-child(1) > div').click()

还有:

driver.find_element_by_xpath('//*[@id="home"]/div/div[2]/div[1]/div/div[1]').click()

下面是“mes posts”框和其他框的代码快照。

【问题讨论】:

标签: python selenium xpath css-selectors google-chrome-headless


【解决方案1】:

尝试使用xpath 而不是css_selector

driver.find_element_by_xpath('xpath_of_your_Div').click()

【讨论】:

  • 是哪个网站/页面?
  • 这是一个私人网站
【解决方案2】:

这是你必须做的。

# get number of the toolboxes first
toolBoxes = len(driver.find_element_by_css_selector("div.boxs div[class^='topBox ']"))

# now you can click on each of them
for boxNumber in range(toolBoxes):
    # you can use either xpath/css to get the nth box and click()
    driver.find_element_by_xpath("(//div[@class='boxs']/div[starts-with(@class,'topBox ')])[" + str(boxNumber+1) + "]").click()
    # waiting here so that you can see the element is clicked (optional)
    time.sleep(2)

【讨论】:

  • 我收到此错误raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"div.boxes div[class^='topBox ]"}`
  • 尝试更新的答案。我提到了“`”而不是',这就是您收到错误的原因。
  • 我之前尝试过,但我得到了同样的错误selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"div.boxes div[class^='topBox ']"}
  • 如果元素被定位,你能试试chrome devtools中的div.boxs div[class^='topBox '] css吗?将类名从boxes 更正为boxs
  • 请发布您下一个问题的 html 代码,这样我们就不会遇到这个错别字:-)
【解决方案3】:
  1. 首先,检查您是否能够找到该元素。如果不是,那么下面的行应该会抛出错误:

    WebElement theButton = driver.find_element_by_xpath('//div[@class='boxs']/div[1]/div');
    

或者,请尝试这个 xpath

    '//div[@class='boxs']/div[1]/div/div/p/span'
  1. 等待元素直到其可点击

    wait = WebDriverWait(driver, 15)
    wait.until(EC.element_to_be_clickable((By.XPATH, my_xpath)))
    
  2. 然后尝试用.click()点击元素

请告诉我您的观察结果,这将有助于解决问题

【讨论】:

    【解决方案4】:

    用这个 css 选择器试试这个代码:

    all_boxes = driver.find_elements_by_css_selector("div.content-box span")
    
    for box_i in range(len(all_boxes)):
        driver.find_elements_by_css_selector("div.content-box span")[box_i].click()
    

    如果您遇到错误,请告诉我,它是什么。

    【讨论】:

    • 感谢您的帮助.. 我收到此错误driver.find_element_by_css_selector("div.boxs > div.topBox > div.content-box")[box_i].click() TypeError: 'WebElement' object is not subscriptable
    • @AbdoRabah 请再试一次,我刚刚更新了我上面的答案......虽然看起来很有希望:)
    • len(all_boxes) 的结果等于 1.. 即使我执行点击它也没有做任何事情
    • 奇怪,让我们将锚点移到顶部。修正了答案。现在怎么样? @AbdoRabah
    • 我的结果还是和以前一样
    猜你喜欢
    • 2015-11-15
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2021-09-08
    • 1970-01-01
    相关资源
    最近更新 更多