首页 > 解决方案 > 我从 python 2.7 迁移到 3.8.5,现在我的代码将无法运行。我正在显示 UnboundLocalError: local variable 'Url_name' referenced before assignment

问题描述

我已经尝试在论坛上寻找答案,但我不明白问题是什么。正如我在问题上所说,我从 python 2.7 切换到 3.x 。我没有故意打开-.-为什么说在赋值之前引用了变量“Url_name”?

此代码在 3.8.5 上运行之前正在运行

file_name = ('Cl.csv')
file = open(file_name, 'w', encoding='UTF8', newline='')
writer = csv.writer(file)
writer.writerow(['Title', 'Price', 'Location', 'Url_name'])


def givesProductlink(products):
    global link
    print (products)
    if products == 'heavy-equipment' or products == 'he':
        link = 'd/heavy-equipment/search/hva?min_price=1000'
    elif products == 'cars' or products == 'cars-trucks':
        link = 'd/cars-trucks/search/cta?min_price=1000'
    elif products == 'atv':
        link = '/search/sna?purveyor-input=all&min_price=500'
    else :
        link = ''


def stepThroughPages(posts, pageLink, n=0):
    #for i in range(len(state)):
        #le = len(state)
    city = state[n]
    l = len(state)
    BASE_URL = 'https://'+ city +'.craigslist.org/'
    driver.get(BASE_URL + pageLink)
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    nextButton =soup.find('a' , class_= 'next')
    posts.extend(soup.find_all('li', class_= 'result-row'))
    if nextButton is None:
        n = n + 1
        if n >= l:
            time.sleep(5)
            return posts
        else:
            return stepThroughPages(posts, link, n )
    return stepThroughPages(posts, nextButton.get('href'), n)


def outputResults(posts):
    for i, post in enumerate(posts):
        image = post.find('img', class_= 'src')
        url = post.find('a', class_= 'result-image gallery')
        Title = post.find('h3', class_ = 'result-heading').text
        Price = post.find('span', class_= 'result-price').text
        if post.find('span', class_= 'result-hood') != None:
            Location = post.find('span', class_= 'result-hood').text
        else:
            Location = 'None'
        for urls in post.find_all('a', class_= 'result-image gallery'):
            Url_name = (urls['href'])
        writer.writerows([Title.encode('UTF-8'), Price.encode('UTF-8'), Location.encode('UTF-8'), Url_name.encode('UTF-8')])

givesProductlink(product)
total_posts = stepThroughPages([], link)
outputResults(total_posts)

file.close()
driver.quit()

标签: python-3.x

解决方案


推荐阅读