会发生什么?
有些容器带有赞助产品,结构略有不同,带有class="item-brand" 的标签是<a>:
<div class="item-container">
<div class="item-sponsored-box">
<div class="item-info">
<div class="item-branding">
<a href="https://www.newegg.com/Sabrent/BrandStore/ID-8281" class="item-brand">
如何解决?
有不同的策略:
-
选择更具体的元素并处理None 结果:
containers[0].find("a",{"class":"item-brand'})
-
只需选择没有赞助产品的容器
containers = soup.select('div.item-container:not(:has(.item-sponsored))')
containers[0].div.div.a
注意: 在新代码中使用find_all() 而不是旧语法findAll()
示例
import requests
from bs4 import BeautifulSoup
url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38'
page = requests.get(url)
soup = BeautifulSoup(page.text)
data = []
for item in soup.find_all('div',{'class':'item-container'}):
data.append({
'title':item.find('a', {'class':'item-title'}).text,
'brand':item.find('a', {'class':'item-brand'}).img['title']
})
print(data)
输出
[{'title': 'ASRock Phantom Gaming D Radeon RX 6500 XT Video Card RX6500XT PGD 4GO', 'brand': 'ASRock'}, {'title': 'GIGABYTE Eagle Radeon RX 6500 XT Video Card GV-R65XTEAGLE-4GD', 'brand': 'GIGABYTE'}, {'title': 'PowerColor AMD Radeon RX 6500XT ITX Gaming Graphics Card 4GB GDDR6', 'brand': 'PowerColor'}, {'title': 'ASUS TUF Gaming Radeon RX 6900 XT Video Card TUF-RX6900XT-O16G-GAMING', 'brand': 'ASUS'}, {'title': 'ASUS Dual Radeon RX 6500 XT Video Card DUAL-RX6500XT-O4G', 'brand': 'ASUS'}, {'title': 'MSI Mech Radeon RX 6500 XT Video Card RX 6500 XT MECH 2X 4G OC', 'brand': 'MSI'}, {'title': 'SAPPHIRE PULSE Radeon RX 6500 XT Video Card 11314-01-20G', 'brand': 'Sapphire Tech'}, {'title': 'MSI Ventus GeForce RTX 3080 Ti Video Card RTX 3080 Ti VENTUS 3X 12G', 'brand': 'MSI'}, {'title': 'EVGA GeForce RTX 3080 Ti XC3 GAMING Video Card, 12G-P5-3953-KR, 12GB GDDR6X, iCX3 Cooling, ARGB LED, Metal Backplate', 'brand': 'EVGA'}, {'title': 'ASUS ROG Strix NVIDIA GeForce RTX 3080 OC Edition Gaming Graphics Card (PCIe 4.0, 12GB GDDR6X, LHR, HDMI 2.1, DisplayPort 1.4a, Axial-tech Fan Design, 2.9-slot, Super Alloy Power II, GPU Tweak II)', 'brand': 'ASUS'}, {'title': 'ASUS Noctua OC Edition GeForce RTX 3070 Video Card RTX3070-O8G-NOCTUA (LHR)', 'brand': 'ASUS'}, {'title': 'GIGABYTE Eagle GeForce RTX 3080 Ti Video Card GV-N308TEAGLE OC-12GD', 'brand': 'GIGABYTE'}]