python - 当驱动程序找不到元素的 xpath 时如何返回“N/A”?
问题描述
我从 url 列表中获得了这个特定的 url,并且就“品牌名称”所在的位置而言,这个特定的 url 与其他 url 具有不同的 xpath 格式。所以我想返回类似字符串 "N/A" 或 None 但我得到的错误
AttributeError: 'NoneType' object has no attribute 'text'
or
AttributeError: 'str' object has no attribute 'text'
这可能是通过在 None 上调用 brand_name.text 或在“N/A”上调用 brand_name.text
我无法更改在我的 row = {} 中调用brand_name.text,因为它可以完美地与其他 url 一起工作品牌名称的其他不同格式的其他网址。
当驱动程序找不到 xpath 时,我需要做什么才能让 brand_name 返回类似“N/A”的内容?
下面是我的代码
import pandas as pd
import csv
from bs4 import BeautifulSoup
from selenium import webdriver
import os
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
chromedriver = " - path to chrome driver -"
driver = webdriver.Chrome(chromedriver)
rows = []
url = https://www.amazon.com/BEAKEY-Foundation-Blending-Flawless-Multi-colored/dp/B01F36JEXE/ref=sr_1_22?dchild=1&keywords=cosmetics&qid=1625014752&sr=8-22
driver.get(url)
# BRAND NAME
try:
brand_name = driver.find_element_by_xpath('//*[@class="a-spacing-small"][.//*[contains(.,"Brand")]]/td[@class="a-span9"]/span')
except (NoSuchElementException, StaleElementReferenceException):
brand_name = None
# SELLER
seller = driver.find_element_by_xpath('(//span[@class="a-truncate-cut"]/span[@class="tabular-buybox-text"])[2]')
# DELIVERY DATE
delivery_date = driver.find_element_by_xpath('//div[@id="mir-layout-DELIVERY_BLOCK"]/div[@class="a-spacing-base"]/b')
row = { 'Brand Name': brand_name.text,
'Seller': seller.text,
'Delivery Date': delivery_date.text
}
if brand_name is not None:
row['Brand Name'] = brand_name.text
else:
row['Brand Name'] = "N/A"
rows.append(row)
driver.close()
df = pd.DataFrame(rows)
df.to_csv('Result2.csv', index=False)
解决方案
您不能在不是 web 元素的东西上调用文本。也许是这样的:
if brand_name is not None:
brand_name_or_none = brand_name.text
else:
brand_name_or_none = "N/A"
row = { 'Brand Name': brand_name_or_none,
'Seller': seller.text,
'Delivery Date': delivery_date.text
}
推荐阅读
- ios - 如何修复“不变违规:requireNativeComponent:在 UIManager 中找不到“RCTFBLoginButton”。”?
- python - 如何在我的数据框中创建一个新变量,用数据框名称填充值?
- ms-access - 访问:用 2 个点递增/递减一个数字
- couchbase - 过滤器上的 Couchbase 二级索引
- javascript - DataTables 动态单元格不会呈现
- reactjs - 节点模块如何解析文件路径?
- android - 如果 onFocusChangeListener 被钩住,TextInputEditText 的奇怪行为
- javascript - Kendo UI - 修改时文本颜色变化
- python-3.x - Python - 无法使用套接字模块将客户端与服务器(在 Windows 2012 R2 上)连接
- nao-robot - 为什么 NAO 的启动会干扰我的默认行为?