使用美丽的汤和scrapy错误给我的错误参考前分配



我正在尝试抓取数据,但他们给我错误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
}

您在try/except中有d3的分配。如果出现错误,赋值就不会发生。如果它发生在第一次迭代时,则不设置变量;如果它发生在以后的迭代中,您将不会得到错误,但是您将把以前的d3值放在字典中。

你应该指定一个默认值在except:块。

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

对于所有其他变量的赋值也应该这样做。

如果你总是得到这个错误,你可能在detail.find()中寻找错误的东西。你应该找出根本原因并解决它。

最新更新