单击基于部分文本匹配的链接
我正在使用 Selenium 2/Webdriver 和 python,我想单击以字符串开头的第一个链接。这是我想出的代码:
def click_link_partial(div_id, partial):
linkdiv = driver.find_element_by_id(div_id)
z = (a.click() for a in linkdiv.find_elements_by_tag_name('a') if a.text.startswith(partial))
z.next()
我对 Python 中的生成器不太熟悉。为什么 a.click() 不立即调用,而是在 z.next() 执行时调用?
使用此代码有什么缺点吗?
I'm using Selenium 2/Webdriver with python and I want to click on the first link that starts with a string. Here's the code I came up with:
def click_link_partial(div_id, partial):
linkdiv = driver.find_element_by_id(div_id)
z = (a.click() for a in linkdiv.find_elements_by_tag_name('a') if a.text.startswith(partial))
z.next()
I'm not very familiar with generators in Python. Why isn't a.click() called immediately, instead of when z.next() executes?
Are there any drawbacks to using this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,请熟悉 Python 的生成器,它们是 Python 武器库中非常强大的工具。阅读另一个问题可以找到 Thomas Wouters 的精彩解释:什么可以你使用 Python 生成器函数做什么?
一旦你读完,你就会意识到生成器只是让你能够延迟计算表达式。
将这段信息与上面的代码联系起来,您会发现
a.click()
实际上不会立即执行,因为预计您会迭代生成器表达式,这就是您的意思已经创建了。这就是为什么您必须发出z.next()
才能实际调用click()
方法。如果您不想发出
z.next()
,并且假设您只想单击第一个部分匹配的链接,则可以按如下方式重写上面的代码:但是,如果您想要要单击所有部分链接的元素,那么您应该从上面的代码中删除
z.next()
并返回要在外部函数/方法中使用的生成器表达式。这是一个例子:希望这有帮助!
First and foremost, please, familiarize yourself with Python's generators, they are a very powerful tool in your Python arsenal. A great explanation by Thomas Wouters can be found by reading another question: What can you use Python generator functions for?
Once you're finished reading, you'll realize that a generator just gives you the ability to evaluate expressions lazily.
Relating this piece of information to your code above, you will find that
a.click()
will not actually execute right away, because it is expected that you iterate over the generator expression, which is what you've created. This is why you must issuez.next()
to actually invoke theclick()
method.If you do not want to issue a
z.next()
, and assuming you just want to click the first partially matched link, you would re-write your code above as follows:However, if you want to click on all the partially linked elements, then you should remove the
z.next()
from your code above and return the generator expression to be used in an outer function/method. Here's an example:Hope this helps!