首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Selenium进行单击?

如何使用Selenium进行单击?
EN

Stack Overflow用户
提问于 2018-02-13 14:57:35
回答 1查看 164关注 0票数 0

我不得不从下面的HTML代码中提取href="/ttt/play"

代码语言:javascript
复制
<div class="collection-list-wrapper-2 w-dyn-list">
  <div class="w-dyn-items">
    <div typeof="ListItem" class="collection-item-2 w-clearfix w-dyn-item">
       <div class="div-block-38 w-hidden-medium w-hidden-small w-hidden-tiny"><a href="https://ttt.io/" target="_blank" property="sameAs" class="link-block-5 w-inline-block"><img src="https://global-uploads.webflow.com/59cf_home.svg" width="16" height="16" alt="Official Link" class="image-28"></a>

       <a property="url" href="/ttt/play" class="link-block-4 w-inline-block">
        <div class="row-7 w-row"><div class="column-10 w-col w-col-2"><img height="25" property="image" src="https://global-fb0edc0001b4b11d/5a77ba9773fd490001ddaaaa_play.png" alt="Play" class="image-23"><h2 property="name" class="heading-34">Play</h2><div style="background-color:#d4af37;color:white" class="text-block-28">GOLD LEVEL</div><div class="text-block-30">HOT</div><div style="background-color:#d4af37;color:white" class="text-block-28 w-condition-invisible">SILVER LEVEL</div></div></div></a>
        </div>

    <div typeof="ListItem" class="collection-item-2 w-clearfix w-dyn-item">

这是我在Python中的代码:

代码语言:javascript
复制
driver = webdriver.PhantomJS()
driver.implicitly_wait(20)
driver.set_window_size(1120, 550)
driver.get(website_url)
tag = driver.find_elements_by_class_name("w-dyn-item")[0]
tag.find_element_by_tag_name("a").click()
url = driver.current_url
print(url)
driver.quit()

当我使用url打印print(url)时,我希望看到url等于website_url/ttt/play,但没有看到它,而是得到了website_url。看起来,单击事件不起作用,新链接也没有真正打开。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-13 15:10:12

当使用.click()时,它必须是“可见的”(使用PhantomJS),而不是隐藏,例如在下拉列表中。

还请确保页面已完全加载。

在我看来,你有两个选择:

  1. 以太使用selenium对其进行修改,然后单击。
  2. 使用java脚本进行实际单击

我强烈建议点击javascript,它更快,更可靠。

下面是一个使事情变得更简单的小包装:

代码语言:javascript
复制
def execute_script(driver, xpath):
    """ wrapper for selenium driver execute_script
    :param driver: selenium driver
    :param xpath: (str) xpath to the element
    :return:  execute_script result
    """
    execute_string = "window.document.evaluate('{}', document, null, 9, null).singleNodeValue.click();".format(xpath)

    return driver.execute_script(execute_string)

包装器基本上实现了使用javascript单击元素的this技术。

然后在selenium脚本中使用包装器,如下所示:

代码语言:javascript
复制
execute_script(driver, element_xpath)

你也可以使它变得更普遍,不仅是点击,而且卷轴和其他魔术。

ps。在我的示例中,我使用了xpath,但您也可以使用css_path --无论在javascript中运行什么。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48769638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档