首页 > 解决方案 > Selenium 找到元素但未按应有的方式返回它

问题描述

我目前正在尝试使用Selenium自动化一些繁琐的任务,这些任务涉及在网站中搜索某些文章,获取结果并将它们存储在文件中。

我的问题是,我正在这样做:

driver.find_element_by_link_text('text')

但是一个Selenium.webbrowser对象正在返回,而不是我需要的链接。

我检查了页面的 HTML 代码,它看起来像

<a href = 'link.html'>text</a>

就像 selenium'doc'所说的那样,它find_element_by_link_text是设计用来处理的。

我的代码基本上如下:

driver.get(base_url)
search_box = driver.find_element_by_class_name('search-field')
search_box.send_keys('text i need to search', Keys.ENTER)
new_url = driver.find_element_by_link_text('text i need to find')
driver.get(new_url)

就像我提到的,new_url它不是函数的有效参数get(),因为它是一个对象。

标签: pythonseleniumweb-scraping

解决方案


答案是根据约翰戈登的说法,你正在尝试使用这个:

.get_attribute("href")

它将href从选定元素返回内部链接。这是官方文档。检查那里了解更多信息。您可能会在那里找到其他有趣的选择。

.get_attribute()你也可以从这里了解一点。


推荐阅读