首页 > 解决方案 > AttributeError:“NoneType”对象没有属性“a”

问题描述

我试图content("GIGABYTE")在下图中使用 python 获取标题。

我用了:

containers= page_soup.findAll("div",{"class":"item-container"})
brand = containers[0].div.div.a.img["title"]

但我根据这一行得到这个错误:

'NoneType' object has no attribute 'a' 

这张图片是一个网站的html内容,我尝试使用网络抓取方法

标签: pythonhtmlwebweb-scraping

解决方案


您可以将 css属性选择器与类选择器结合使用。 表示具有父类的属性的元素。.item-brand img[title]imgtitle.item-brand

import requests
from bs4 import BeautifulSoup
url = 'https://www.newegg.com/Product/ProductList.aspx?Submit=ENE&DEPA=0&Order=BESTMATCH&Description=graphics+card&N=-1&isNodeId=1'
res  = requests.get(url, headers  = {'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(res.content, 'lxml')

items = [item['title'] for item in soup.select('.item-brand img[title]')]
print(items)

推荐阅读