【问题标题】:How to check if an element exists in xpath and return null/no value if it doesn't?如何检查 xpath 中是否存在元素,如果不存在则返回 null/no 值?
【发布时间】:2021-06-30 04:27:31
【问题描述】:

我正在尝试从给定存储在“数据”中的 url 列表的网站中抓取数据。

我注意到一些 url 没有“og_price”和“discount”的 xpath,我收到 NoSuchElement 错误,或者直接说“og_price”和“discount”未定义大概是因为某些 url 没有有那个 xpath。

我想检查 url 中是否存在 xpath(我试图用 try-except 来做)并返回一个空值或只是字符串“no”,但我被困在如何做到这一点上,因为我稍后会调用“ "og_price" 和 "discount" 上的 .text" 会说 'str' 对象没有属性 '.text'

for url in data:
    driver.get(url)
    item_name = driver.find_element_by_xpath('//span[@id="productTitle"]')
    brand_name = driver.find_element_by_xpath('//*[@class="a-spacing-small"][.//*[contains(.,"Brand")]]/td[@class="a-span9"]/span')
    price = driver.find_element_by_xpath('//div[@class="a-section a-spacing-micro"]/span[@id="price_inside_buybox"]')
    try: 
        og_price = driver.find_element_by_xpath('//span[@class="priceBlockStrikePriceString a-text-strike"]')
        discount = driver.find_element_by_xpath('//td[@class="a-span12 a-color-price a-size-base priceBlockSavingsString"]')
    except NoSuchElementException:
        og_price = null
        discount = null
    

    row = { 'Item Name': item_name.text,
            'Brand Name': brand_name.text,
            'Price': price.text,
            'Original Price': og_price.text,
            'URL': url
          }

【问题讨论】:

    标签: python python-3.x selenium web-scraping xpath


    【解决方案1】:

    @Harry Kim 检查元素是否存在的正确方法是像上面那样将检查包装在 try/catch 块中。要解决空对象异常的问题,您可以在将元素分配给行映射之前进行 if 检查。类似的,

        try: 
            og_price = driver.find_element_by_xpath('//span[@class="priceBlockStrikePriceString a-text-strike"]')
            discount = driver.find_element_by_xpath('//td[@class="a-span12 a-color-price a-size-base priceBlockSavingsString"]')
        except NoSuchElementException:
            og_price = None
            discount = None
        
    
        row = { 'Item Name': item_name.text,
                'Brand Name': brand_name.text,
                'Price': price.text,
                'URL': url
              }
        if og_price is not None:
              row["Original Price"] = og_price.text
        else:
              row["Original Price"] = "N/A"
    

    如果您有明确定义的 css 标签,使用 find_element_by_css_selector 或 find_element_by_id 等函数也是一个好主意。只有当目标元素确实具有正确的 id 或 css 标签时,我们才会使用 Xpath。

    【讨论】:

    • 不确定您的意思是解决空对象异常的问题?如果 xpath 不存在,我想返回一个空值或字符串“no”?
    • @HarryKim 您可以在不存在的情况下将对象分配给 None ,并且在访问 text 属性之前进行 None 检查。已使用该逻辑更新了代码。
    • 我应该把 if-else 语句放在哪里?另外,我尝试将它放在 row = {'Item Name': item_name.text ...} 之前,我收到错误“'str' object has no attribute 'text'”,我认为这是因为我正在调用 .text关于“不适用”
    • 当我把它放在 row = {'Item Name': item_name.text ...} 之后,我得到“'NoneType' object has no attribute 'text'”
    • 很高兴它帮助了你@HarryKim。编码愉快。
    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    相关资源
    最近更新 更多