scrapy 作业前用靓汤和零碎的错误给予我那个错误参考

pvabu6sv  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(105)

我试图刮数据,但他们给予我错误UnboundLocalError: local variable 'd3' referenced before assignment我如何可以解决这些错误任何解决方案请建议我我搜索许多解决方案,但我找不到任何解决方案,帮助我,如果你有任何解决方案,然后建议我这些是页面链接https://rejestradwokatow.pl/adwokat/abaewicz-agnieszka-51004

import scrapy
from scrapy.http import Request
from scrapy.crawler import CrawlerProcess
from bs4 import BeautifulSoup

class TestSpider(scrapy.Spider):
    name = 'test'
    start_urls = ['https://rejestradwokatow.pl/adwokat/list/strona/1/sta/2,3,9']
    custom_settings = {
        'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
        'DOWNLOAD_DELAY': 1,
        'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
        }

    def parse(self, response):
        soup=BeautifulSoup(response.text, 'html.parser')
        tra = soup.find_all('td', class_='icon_link')
        for links in tra:
            for link in links.find_all('a', href=True):
                comp = link['href']
                yield Request(comp, callback=self.parse_book)

    def parse_book(self, response):
        soup=BeautifulSoup(response.text, 'html.parser')
        details = soup.find_all('div', class_='line_list_K')
        for detail in details:
            try:
                status = detail.find(
                    'span', string='Status:').findNext('div').getText()
            except:
                pass

            try:
                d1 = detail.find('span', string='Data wpisu w aktualnej izbie na listę adwokatów:').findNext(
                    'div').getText()
            except:
                pass

            try:
                d3 = detail.find('span', string='Ostatnie miejsce wpisu:').findNext(
                    'div').getText()
            except:
                pass

            try:
                d4 = detail.find('span', string='Stary nr wpisu:').findNext(
                    'div').getText()
            except:
                pass

            try:
                d5 = detail.find('span', string='Zastępca:').findNext(
                    'div').getText()
            except:
                pass

            yield{
               'status':status,
               "d1":d1,
               "d3":d3,
               "d4":d4,
               "d5":d5
               }
fae0ux8s

fae0ux8s1#

try/except中有一个对d3的赋值,如果出错,赋值就不会发生,如果在第一次迭代中出错,变量就不置位;如果在以后的迭代中发生这种情况,您不会得到错误,但是您会将d3的前一个值放入字典中。
您应该在except:块中指定一个默认值。

try:
                d3 = detail.find('span', string='Ostatnie miejsce wpisu:').findNext(
                    'div').getText()
            except:
                d3 = ''

您也应该对所有其他变量赋值执行此操作。
如果你总是得到这个错误,你可能在detail.find()中寻找错误。你应该找出根本原因并修复它。

相关问题