【问题标题】:Selenium 'list' object has no attribute 'text'Selenium 'list' 对象没有属性 'text'
【发布时间】:2021-01-22 12:07:43
【问题描述】:

所以我使用 python 和 selenium 来抓取丝芙兰 page 上的产品标题。

url = 'https://www.sephora.com/ca/en/shop/face-makeup'

driver.get(url)  
time.sleep(2)
   
browser = scrollDown(driver, 20)

# this selected the div for every product on the page
products = driver.find_elements_by_class_name('css-79elbk')

for product in products:
    title = product.find_elements_by_xpath('/html/body/div[1]/div[2]/div/div/div/div[2]/div[1]/main/div[3]/div/div[1]/div[1]/div[1]/a/div/div[4]/span[2]').text
    print(title)

问题是当我运行它时我得到Line 48: AttributeError: 'list' object has no attribute 'text'。标题位于嵌套在 div 中的跨度中。我已经在一个带有文本的普通 div 上尝试过这个,它没有问题。

【问题讨论】:

  • 请注意,您使用的函数通过 xpath 查找元素s(注意 find_elements_by_xpath 中的“s”)。该函数返回一个列表,而不是单个对象。
  • @ShaneBishop 摆脱了我提到的错误,但现在它只返回页面上的第一个产品价格 x 产品数量。

标签: python selenium selenium-webdriver xpath


【解决方案1】:

出现错误是因为这一行:

.find_elements_by_xpath('/html/body/div[1]/div[2]/div/div/div/div[2]/div[1]/main/div[3]/div/div[1]/div[1]/div[1]/a/div/div[4]/span[2]').text

以上返回一个列表。

.text 方法用于.find_element_*(不带s

但简单来说,您可以通过 css 选择器使用以下值刮取标题:div[data-comp="ProductDisplayName "] span[data-at="sku_item_name"]

试试下面的代码:

url = 'https://www.sephora.com/ca/en/shop/face-makeup'

driver.get(url)  
time.sleep(2)
   
browser = scrollDown(driver, 20)

titles = driver.find_elements_by_css_selector('div[data-comp="ProductDisplayName "] span[data-at="sku_item_name"]')
for title in titles:
    print(title.text)

要刮品牌,您只需将选择器更改为:div[data-comp="ProductDisplayName "] span[data-at="sku_item_brand"]

【讨论】:

  • 谢谢!我什至不知道您可以使用数据属性进行刮擦。
猜你喜欢
  • 2018-09-28
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-28
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2023-01-27
相关资源
最近更新 更多