1

我很感激在这个问题上的任何帮助。

我正在尝试单击(展开)此页面上的所有年份月份元素:

<tbody ng-repeat="year">
   <tr class="year expandable title">
      <th><a>2020</a></th>
   </tr>
   <tr class="month expandable title ng-hide">
      <th><a><span class="display">December 2020</span></a></th>
   </tr>
    <!-- [...] ALL OTHER MONTHS, SAME STRUCTURE -->
</tbody>
<tbody ng-repeat="year">
   <tr class="year expandable title">
      <th><a>2019</a></th>
   </tr>
   <tr class="month expandable title ng-hide">
      <th><a><span class="display">December 2019</span></a></th>
   </tr>
    <!-- [...] ALL OTHER MONTHS, SAME STRUCTURE -->
</tbody>

在下面尝试此代码时,我总是收到查找错误。

for y in find_all(S('.year.expandable')):
  click(y)

for m in find_all(S('.month.expandable')):
  click(m)

这是回溯:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/local/lib/python3.9/site-packages/helium/__init__.py", line 273, in click
    _get_api_impl().click_impl(element)
  File "/usr/local/lib/python3.9/site-packages/helium/_impl/__init__.py", line 202, in click_impl
    self._perform_mouse_action(element, self._click)
  File "/usr/local/lib/python3.9/site-packages/helium/_impl/__init__.py", line 37, in f_decorated
    result = f(self, *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/helium/_impl/__init__.py", line 56, in f_decorated
    return f(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/helium/_impl/__init__.py", line 240, in _perform_mouse_action
    self._manipulate(element, lambda wew: action(wew.unwrap(), offset))
  File "/usr/local/lib/python3.9/site-packages/helium/_impl/__init__.py", line 301, in _manipulate
    driver.last_manipulated_element = gui_or_web_elt.perform(action)
  File "/usr/local/lib/python3.9/site-packages/helium/_impl/__init__.py", line 648, in perform
    raise LookupError()
LookupError

不知道为什么,但它可以工作如果我只点击一个元素click(S('.year.expandable'))

知道有什么问题吗?

4

1 回答 1

0

DOM 似乎在交互时发生变化,因此出现错误。我找到了一种不使用 Helium 的解决方法。我编写了一个自定义函数,用于driver.find_elements_by_xpath(xpath)使用 selenium 发现和单击 DOM 元素。

    driver = helium.get_driver()
    for h in range(len(driver.find_elements_by_xpath(xpath))):
        try:
            sleep(random.uniform(1,1.25)) #otherwise misclicks
            highlight(S(xpath))     #to avoid StaleElement Exceptions
            S(xpath).web_element.click()
        except Exception as e:
            print(e)
            continue

代码可以解决问题。不完全确定为什么,但我必须添加highlight(S(xpath))以确保点击通过,否则代码会随机返回 StaleElement Exception.

我知道这很hacky,但如果其他人有更好的解决方案,请随时发表评论。

于 2021-12-05T11:31:03.257 回答