首页 > 解决方案 > 使用 xpath + id 获取 href

问题描述

我有一个搜索结果列表 来自该站点的 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')

标签: pythonhtmlseleniumxpath

解决方案


你想要的是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,现在在 selenium 中我们有一种方法get_attribute来提取所需的属性。

希望你觉得这有帮助!


推荐阅读