使用xpath + id获取href

时间:2018-11-20 16:45:15

标签: python html selenium xpath

我有一个搜索结果列表,来自this site的9个搜索结果,我希望获得搜索结果中每个项目的href链接。

以下是第一项,第二项和第三项链接的xpath和选择器:

'//*[@id="search-results"]/div[4]/div/ctl:cache/div[3]/div[1]/div/div[2]/div[2]/div[2]/p[4]/a'

#search-results > div.c_408104 > div > ctl:cache > div.product-list.grid > div:nth-child(8) > div > div.thumbnail > div.caption.link-behavior > div.caption > p.description > a


'//*[@id="search-results"]/div[4]/div/ctl:cache/div[3]/div[2]/div/div[2]/div[2]/div[2]/p[4]/a'

#search-results > div.c_408104 > div > ctl:cache > div.product-list.grid > div:nth-child(13) > div > div.thumbnail > div.caption.link-behavior > div.caption > p.description > a


'//*[@id="search-results"]/div[4]/div/ctl:cache/div[3]/div[4]/div/div[2]/div[2]/div[2]/p[2]/a'

#search-results > div.c_408104 > div > ctl:cache > div.product-list.grid > div:nth-child(14) > div > div.thumbnail > div.caption.link-behavior > div.caption > p.description > a

我尝试过:

browser.find_elements_by_xpath("//a[@href]")

,但这将返回页面上的所有链接,而不仅仅是搜索结果。我也尝试过使用id,但是不确定什么是正确的语法。

browser.find_elements_by_xpath('//*[@id="search-results"]//a')

1 个答案:

答案 0 :(得分:1)

您想要的是所有结果中的attribute="href" ...

所以我给你看一个例子:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


url = 'https://www.costco.com/sofas-sectionals.html'

chrome_options = Options()
chrome_options.add_argument("--start-maximized")
browser = webdriver.Chrome("C:\workspace\TalSolutionQA\general_func_class\chromedriver.exe",
                           chrome_options=chrome_options)


browser.get(url)
result_xpath = '//*[@class="caption"]//a'
all_results = browser.find_elements_by_xpath(result_xpath)
for i in all_results:
    print(i.get_attribute('href'))

所以我在这里所做的只是获取我知道的所有具有链接的元素,并将它们保存到all_results,现在在硒中,我们有了方法get_attribute来提取所需的属性

希望这对您有所帮助!

相关问题