【问题标题】:Why isn't selenium clicking a button in python?为什么硒不单击python中的按钮?
【发布时间】:2018-10-02 00:41:56
【问题描述】:

我正在为按钮本身使用 xpath 选择器,当我尝试单击时,selenium 给我一个错误selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ember1355"]/button"}。我想做的是使用 selenium 与linkedin中的人联系。当我搜索特定术语时,我想提取所有显示“连接”的配置文件并单击每个按钮。 html是

<div class="search-result__actions">
        <div id="ember3093" class="ember-view">    
            <button aria-label="Connect with Persons name" class="search-result__actions--primary button-secondary-medium m5" data-control-name="srp_profile_actions" data-ember-action="" data-ember-action-3096="3096">Connect</button>   
        <div id="ember3099" class="ember-view"><div id="ember3100" class="ember-view"><!----></div></div>
        </div>
        </div>

我的代码是:

if each.find('div', class_='search-result__actions').find('div').text.strip() == "Connect":
    id = each.find('div', class_='search-result__actions').find('div')['id']
    id = '//*[@id="'+id+'"]'
    print(id)
    #this is where the code isn't working
    driver.find_element_by_xpath('//*[@id="ember1355"]/button').click()

【问题讨论】:

  • 要选择的元素不在视野范围内。我建议在尝试点击之前滚动到元素。
  • 是否可以滚动到该特定元素?

标签: python selenium


【解决方案1】:

尽量避免使用Xpath

试试 css_selector

# Finds the right css selector
button = driver.find_element_by_css_selector('.search-result__actions--primary')
# Clicks the button
driver.execute_script("arguments[0].click();", button)

【讨论】:

  • 这是更好的方法吗?另外,它可以单击屏幕外的链接还是我必须导航到屏幕上的链接?
  • Css 选择器比 xpath 执行得更好,并且更易于阅读。您上面的问题与屏幕外的元素无关,而是您的 xpath 中的问题。 Selenium click() 方法在执行单击操作之前尝试滚动。如果你想在点击这里之前滚动:el = driver.find_element_by_css_selector('#ember1355 .search-result__actions--primary') self.driver.execute_script("arguments[0].scrollIntoView();", el)跨度>
  • 感谢您的洞察力。但是,我尝试了该代码,但我收到了错误,即该按钮此时不可点击,另一个元素将收到点击。我尝试了很多不同的东西,但似乎没有任何效果让它点击按钮。有什么想法吗?
  • 从您的 HTML id 应该是 ember3093 而不是 ember1355?
    如果搜索返回一个唯一元素,您能否使用此代码检查:
    el = driver.find_elements_by_css_selector('#ember1355 .search-result__actions--primary')
    此代码应该返回一个元素列表。如果有不止一个元素,我们需要更具体的定位器值。
  • Ember3093 和 ember1355 看起来像是页面上特定于个人的不同元素。 LinkedIn 为每个人更改该 ID,我有我的脚本来抓取该信息。当我尝试单击该按钮时,我不断收到该元素不可单击的错误,并且单击转到 a 标记。在 html 中,按钮没有 a 标签。这很奇怪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-02
  • 2023-01-11
  • 2021-12-08
  • 1970-01-01
  • 2021-02-20
  • 2023-03-26
  • 2016-05-29
相关资源
最近更新 更多