环境 python2.7 win10 64位
一个爬虫,没有函数,里面的变量在循环里能正常使用,将这些代码用一个function包起来,运行方法,说变量未定义。这是为什么啊?变量均是在函数内部定义,使用的时候是在变量下面的一个循环里使用。
手机码字谢谢
不好意思这是代码):
for ava in avtreeres:
av_day=''
for ix in allcontentx:
if(u'生日' in ix):
print '是存在生日的'
av_day=ix[4:]
print av_day
else:
av_day='11'
if actorhasyesdata!=None and actorhasyesdata!='':
print 'has'
else:
print av_day #这里就出错了,说未定义,并且av_day 的值不是11
更新代码:
allcontentx=avinfox.xpath("/html/body/div/div/div[1]/div[2]/p/text()")
for ix in allcontentx:
if(u'生日' in ix):
print '是存在生日的'
av_day=ix[4:]
print av_day
else:
av_day=''
if(u'身高' in ix):
print '是有身高的'
av_height=ix[4:]
print av_height
else:
av_height=0
avinfoxr=avinfox.xpath("/html/body/div/div/div[1]/h2[1]/a[2]/text()")
print avinfoxr[0]
# sql actor
actorhas="SELECT namex FROM actor WHERE namex='%s'" % (avinfoxr[0])
actorhasyes=cur.execute(actorhas)
actorhasyesdata=cur.fetchone()
db.commit()
if actorhasyesdata!=None and actorhasyesdata!='':
print 'has'
else:
sqlactor="INSERT INTO actor (namex,birth,height) VALUES ('%s','%s',%s)" % (avinfoxr[0],av_day,av_height)
print sqlactor
ks=cur.execute(sqlactor)
db.commit()