首页 > 解决方案 > 使用 selenium_python 抓取类下的属性

问题描述

我正在尝试从主类下的 data-asin 中抓取信息

<div class = "s-main-slot s-result-list s-search-results sg-row">

在此处输入图像描述

我需要前六个 asins 的数据为:B081G75GPQ、B081FBQZ95、B084HZ7PV3、B084HZFBRZ、B087N66CJT、B07TYQ3KYX 并将它们粘贴到 Excel 中的一行。

直到现在我尝试了这个但没有工作,还有另一种方式来访问这个信息并在 excel 中复制?

elements = driver.find_elements_by_class_name(
        's-main-slot s-result-list s-search-results sg-row')
    for e in elements:
        print(e.get_attribute('data-asin'))
    else:
        print('not found')

标签: pythonselenium

解决方案


使用 selenium 和复合类选择器查看此问题: https ://stackoverflow.com/a/32044129/1387701

from selenium.webdriver.common.by import By
driver.findElement(By.cssSelector(".s-main-slot.s-restul-list"));

看起来你可能想抓住那个元素,然后找到它下面的 div。

list = driver.find_element_by_css_selector(By.cssSelector(".s-main-slot.s-result-list"));
divs = list.find_elements_by_xpath("./div")
for d in div:
        print(e.get_attribute('data-asin'))

推荐阅读