python - 使用 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')
解决方案
你想要的是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
来提取所需的属性。
希望你觉得这有帮助!
推荐阅读
- java - IntelliJ 调试器:计算函数被调用的次数
- reactjs - React Native Navigation 不存在
- python - 为什么我在 SQLite 中的外键被损坏了?
- r - 提取 PCA 分析的 PCn
- c - va_start 意外行为
- java - 为什么onFinish在android studio中运行多次?
- reactjs - 使用 React 和 Nginx 编写 Docker
- python - 列表索引有重复的索引号
- android - Android Kotlin:在视图上翻译动画不起作用
- javascript - TypeError:this.state.tasks.map 不是函数