我有一个搜索结果列表,来自本站的9个搜索结果,我想获得搜索结果中每个项目的href链接。
下面是第1、第2和第3项链接的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')发布于 2018-11-20 17:49:43
你要的是所有结果的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方法来提取所需的属性。
希望你觉得这有帮助!
https://stackoverflow.com/questions/53397678
复制相似问题