当驱动程序找不到元素的 xpath 时如何返回"N/A"?



我有一个url列表中的特定url,这个特定url的xpath格式与其他url不同;品牌名称";位于。所以我想返回一个类似字符串的东西";N/A";或者没有,但我得到的错误

AttributeError: 'NoneType' object has no attribute 'text'
or
AttributeError: 'str' object has no attribute 'text'

这可能来自于在None上调用brand_name.text或在"0"上调用brand_name.text;N/A";

我无法更改在我的行={}中调用brand_name.text,因为这与其他url完美配合我也不想再编写另一个代码,在这个特定的url中查找brand_name的xpath,因为brand_name还会有其他不同格式的url。

我需要做些什么才能让brand_name返回类似";N/A";当驱动程序找不到它的xpath时?

下面是我的代码

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
}

最新更新