首页 > 解决方案 > Python Webscraping - AttributeError:'NoneType'对象没有属性'text'

问题描述

在尝试使用 BeautifulSoup、Selenium 和 Pandas 将笔记本电脑的价格、评级和产品从 Flipkart 抓取到 CSV 文件时,我需要一些帮助。问题是当我尝试将抓取的项目附加到空列表中时,出现错误AttributeError: 'NoneType' object has no attribute 'text' 。

from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup


chrome_option = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path = "C:/Users/folder/PycharmProjects/chromedriver.exe")
#flipkart website
driver.get("https://www.flipkart.com/laptops/~cs-g5q3mw47a4/pr?sid=6bo%2Cb5g&collection-tab-name=Browsing&wid=13.productCard.PMU_V2_7")


products = []
prices = []
ratings = []


content = driver.page_source
soup = BeautifulSoup(content, 'lxml')
for item in soup.findAll('a', href = True, attrs={'class' : '_1fQZEK'}):
    name = item.find('div', attrs={'class' : '_4rR01T'})
    price = item.find('div', attrs={'class' : '_30jeq3 _1_WHN1'})
    rating = item.find('div', attrs={'class' : '_3LWZlK'})
    
    products.append(name.text)
    prices.append(price.text)
    ratings.append(rating.text)
    

    df = pd.DataFrame({'Product Name': products,
                        'Price': prices,
                        'Rating': ratings})

    df.to_csv(r"C:\Users\folder\Desktop\webscrape.csv", index=True, encoding= 'utf-8')

标签: pythonseleniumweb-scrapingtextattributeerror

解决方案


您应该使用.contentsor.get_text()代替.text。另外,请尝试关心 NoneType :

products.append(name.get_text()) if name else ''
prices.append(price.get_text()) if price else ''
ratings.append(rating.get_text()) if ratings else ''

推荐阅读