python-3.x - 我从 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()
解决方案
推荐阅读
- objective-c - 崩溃 - iPhone XS 中的 AVCaptureSessionPresentMedium
- google-apps-script - AppMaker 达到 Gmail 配额
- css - 在浏览器之外使用 CSS
- batch-file - 使用 if not exist 命令进行广泛的目录搜索
- asp.net - 由于 ASPX 重写,不会执行信号器/集线器
- java - 如何强制卸载 java 更新?
- javascript - Vue-tables-2 使用复选框选择多行,然后将行推送到新数组
- javascript - 我不能将 JSON 数据放入数组中
- c# - 对 INavigationService 类型的引用声称它是在 Prism 中定义的,但找不到它
- ms-access - 访问:计算 2 列中的出现次数