python - 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')
解决方案
您应该使用.contents
or.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 ''
推荐阅读
- microcontroller - 使用 pic10f222 内部绝对电压参考
- macos - 如何使用 Mac OS X 辅助功能 API 检索活动窗口 URL
- c# - ASP.NET MVC 全局身份验证和 AllowAnonymous
- r - R中大表的相关矩阵问题
- apache-spark - Pyspark 从列中获取最新更新的值
- service-fabric-stateful - Service Fabric StatelessService 无法访问同一个集群中的 StatefulService
- action - 每天运行 Odoo 自动化操作
- javascript - getElementById 未正确接收输入/未显示 - javascript
- c# - Excel:将类似 JSON 的数据 {column1name = value, column2name = value} 转换为带有列标题的普通 Excel 表
- c# - LINQ - 如何对过滤数据集的所有列求和