【问题标题】:Bypass NoneType Exception while collecting data收集数据时绕过 NoneType 异常
【发布时间】:2019-08-08 17:48:25
【问题描述】:

我目前正在循环通过一个 XML 响应并希望匹配一个特定的 ID。然后,我将回溯到父节点以收集与其关联的其他数据。在此过程中,如果 ID 不匹配,我将无法查看父节点,因为该值不存在并出现 NoneType 异常错误。目标是捕获引发此错误的值并绕过异常错误,以便我可以继续浏览我的列表。

我已经尝试使用 if 语句将值更改为字符串,但仍然抛出错误

import requests
from bs4 import BeautifulSoup
import csv


url = "https://google.com/Clicks"

payload = {
            "start_date":"08/07/2019 21:42:00",
            "end_date":"08/07/2019 21:42:59",
            "offer_id":"284"
            }

r = requests.get(url, params=payload)

##print(r.text)
response = BeautifulSoup(r.text,'lxml')

with open('TrackingIDs.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for data in csv_reader:
        trackingID = data['ID']



        matchedID = response.find(text=trackingID)
        parent = matchedID.parent.parent
        campaignID = parent.find('campaign_id').string
        affiliateID = parent.find('source_affiliate_id').string
        subID = parent.find('sub_id_1').string
        print(campaignID)
        print(affiliateID)
        print(subID)

从我的 CSV 文件导入我的 Tracking ID 的数据并且找不到该 ID 后引发错误。

任何建议将不胜感激。

【问题讨论】:

    标签: xml python-3.x beautifulsoup


    【解决方案1】:

    Try 和 Expect 块成功了:

    try:
                matchedID = response.find(text=trackingID)
                parent = matchedID.parent.parent
            except (AttributeError, NameError):
                print('ID not Found:', data['ID'])
            else:
                campaignID = parent.find('campaign_id').string
                affiliateID = parent.find('source_affiliate_id').string
                subID = parent.find('sub_id_1').string
                print('Tracking ID:', matchedID)
                print('Campaign ID:', campaignID)
                print('Affiliate ID:', affiliateID)
                print('Sub ID:', subID)
                c.writerow([matchedID, campaignID, affiliateID, subID])
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多