python - 我在网页抓取 python 时遇到问题
问题描述
我必须从 ebay.com 抓取数据,我的抓取项目是:“汽车名称”、“制造”、“型号”、“传输”和“价格”,我已经抓取了所有这些项目,但是当编写代码时传输',告诉我这个错误:
Traceback (most recent call last):
File "C:/Users/Oogway/PycharmProjects/web_scraping1/test.py", line 27, in <module>
trans_of_car = title_trans.text
AttributeError: 'NoneType' object has no attribute 'text'
而且它不会刮掉“传输”项目!*tip : 从“传输”中刮掉一些项目,然后显示错误,并在显示错误后刮掉“传输”的拖曳项目。
代码:
import requests
from bs4 import BeautifulSoup
import re
url = 'https://www.ebay.com/b/Cars-Trucks/6001?_fsrp=0&_sacat=6001&LH_BIN=1&LH_ItemCondition=3000%7C1000%7C2500&rt=nc&_stpos=95125&Model%2520Year=2020%7C2019%7C2018%7C2017%7C2016%7C2015'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
ebay_cars = soup.find_all('li', class_='s-item')
for car_info in ebay_cars:
title_div = car_info.find('div', class_='s-item__wrapper clearfix')
title_sub_div = title_div.find('div', class_='s-item__info clearfix')
title_p = title_sub_div.find('span', class_='s-item__price')
title_tag = title_sub_div.find('a', class_='s-item__link')
title_maker = title_sub_div.find('span', class_='s-item__dynamic s- item__dynamicAttributes1')
title_model = title_sub_div.find('span', class_='s-item__dynamic s-item__dynamicAttributes2')
title_trans = title_sub_div.find('span', class_='s-item__dynamic s-item__dynamicAttributes3')
name_of_car = title_tag.text
price_of_car = title_p.text
maker_of_car = title_maker.text
model_of_car = title_model.text
trans_of_car = title_trans.text
解决方案
这是因为,此特定条目的网站中不存在此元素,这意味着它是None
. 只需将语句放在try , except
导致此错误的子句中,这将有所帮助..
在这种情况下...
try:
trans_of_car = title_trans.text
except:
trans_of_car = ''
推荐阅读
- javascript - 参数声明本身
- visual-studio-code - 在 Visual Code 终端上找到 nvm 和 gulp,但在 linux 终端上没有
- networking - 测验中的子网问题需要解释(见图)
- flutter - Flutter 无法从 url 加载图片
- java - 不支持 Spring Boot 405 POST 方法,但 GET 方法有效
- python - 字符图片网格 Python ATBS 索引超出范围
- c#-9.0 - 这是什么 C# 功能?
- javascript - 当使用新查询推送相同的路由时,创建的钩子不再运行
- swift - swift _ 推入 ViewController 会出现黑屏
- visual-studio-code - macOS 中的文本编辑器对两个带有 ANSI 转义码的文件的差异有问题吗?