首页 > 解决方案 > 当驱动程序找不到元素的 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)

标签: pythonseleniumselenium-webdriverweb-scrapingxpath

解决方案


您不能在不是 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
      }

推荐阅读