'list' 对象在遍历 WebElements 时没有属性 'get_attribute'

Bri*_*ruz 4 python selenium web-scraping selenium-chromedriver selenium-webdriver

我正在尝试使用 Python 和 Selenium 来抓取网页上的多个链接。我正在使用find_elements_by_xpath并且我能够找到一个元素列表,但是我无法更改返回到实际href链接的列表。我知道find_element_by_xpath有效,但这仅适用于一种元素。

这是我的代码:

path_to_chromedriver = 'path to chromedriver location'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

browser.get("file:///path to html file")

all_trails = []

#finds all elements with the class 'text-truncate trail-name' then 
#retrieve the a element
#this seems to be just giving us the element location but not the 
#actual location

find_href = browser.find_elements_by_xpath('//div[@class="text truncate trail-name"]/a[1]')
all_trails.append(find_href)

print all_trails
Run Code Online (Sandbox Code Playgroud)

此代码返回:

<selenium.webdriver.remote.webelement.WebElement 
(session="dd178d79c66b747696c5d3750ea8cb17", 
element="0.5700549730549636-1663")>, 
<selenium.webdriver.remote.webelement.WebElement 
(session="dd178d79c66b747696c5d3750ea8cb17", 
element="0.5700549730549636-1664")>,
Run Code Online (Sandbox Code Playgroud)

我期待all_trails阵列是像链接列表:www.google.com, www.yahoo.com, www.bing.com

我尝试遍历all_trails列表并运行列表上的get_attribute('href')方法,但出现错误:

错误图片

有谁知道如何将 selenium WebElement 转换为 href 链接?

任何帮助将不胜感激 :)

Deb*_*anB 7

让我们看看您的代码中发生了什么:

对相关人员没有任何可见性,HTML似乎以下行返回两个WebElementsin ,然后将List find_href其附加到:all_trails List

find_href = browser.find_elements_by_xpath('//div[@class="text truncate trail-name"]/a[1]')
Run Code Online (Sandbox Code Playgroud)

因此,当我们打印List all_trails两者时,都会WebElements打印出来。因此没有错误。

按照错误捕捉拍摄你提供,你试图调用get_attribute("href")了一个方法,List这是不支持。因此你会看到错误:

'List' Object has no attribute 'get_attribute'
Run Code Online (Sandbox Code Playgroud)

解决方案 :

要获取href属性,我们必须List按如下方式迭代:

find_href = browser.find_elements_by_xpath('//your_xpath')
for my_href in find_href:
    print(my_href.get_attribute("href"))
Run Code Online (Sandbox Code Playgroud)