【发布时间】:2018-05-23 22:33:40
【问题描述】:
我正在尝试使用 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
此代码正在返回:
<selenium.webdriver.remote.webelement.WebElement
(session="dd178d79c66b747696c5d3750ea8cb17",
element="0.5700549730549636-1663")>,
<selenium.webdriver.remote.webelement.WebElement
(session="dd178d79c66b747696c5d3750ea8cb17",
element="0.5700549730549636-1664")>,
我希望all_trails 数组是一个链接列表,例如:www.google.com, www.yahoo.com, www.bing.com。
我尝试循环遍历 all_trails 列表并在列表中运行 get_attribute('href') 方法,但出现错误:
有人知道如何将 selenium WebElement 转换为 href 链接吗?
任何帮助将不胜感激:)
【问题讨论】:
-
注意
find_elements_by_xpath是复数;它返回一个列表。当您将生成的内容附加到列表时,您将获得列表列表(不是列表)。 -
请在此处粘贴您的 html
标签: python selenium selenium-webdriver web-scraping selenium-chromedriver