我正在Python上研究Selenium。我需要对8000多个URL进行相同的过程,所以我定义了以下函数:
def obtenerFrecuencia(paradero):
driver = webdriver.Chrome(r'C:phantomjs-2.1.1-windowsbinchromedriver.exe') # Optional argument, if not specified will search path.
driver.get(paradero)
sleep(random.uniform(0, 0.3))
id_base = driver.find_elements_by_xpath('//h3[@class="focus"]')
for info in id_base: # id
variableunica = str(info.get_attribute("outerText")
driver.quit()
return variableunica
我把8000个URL保存在一个名为链接的列表中。
当我继续运行以下代码来存储我的代码的发现时:
frecuencia = []
for link in links:
temp = obtenerFrecuencia(link)
frecuencia.append(temp)
我得到以下错误:
UnboundLocalError:在分配之前引用了本地变量"variableunica">
但是,我没有在文档中的任何地方引用局部变量,所以我真的不明白为什么会出现这个问题。我一直在阅读其他有同样问题的问题,但它们是无关的,因为到目前为止,还没有提到任何解决方案,甚至与我的问题有关。所以我觉得在这里发布这个问题会很有帮助。
此外,该错误在代码的不同迭代中显示,最高值为500,最低值为21。所以,代码肯定是有效的,但我认为它可以改进,以便连续获得8000个URL的信息并避免这个错误。
因此问题如下:
- 如何避免此错误(如何以这种方式定义变量(
- 既然我以前没有定义那个局部变量,为什么会显示它
您在使用前没有声明variableunica如果您的代码没有进入信息循环,那么在分配之前引用了变量variableunica
def obtenerFrecuencia(paradero):
driver = webdriver.Chrome(r'C:phantomjs-2.1.1-windowsbinchromedriver.exe') # Optional argument, if not specified will search path.
driver.get(paradero)
sleep(random.uniform(0, 0.3))
id_base = driver.find_elements_by_xpath('//h3[@class="focus"]')
variableunica=""
for info in id_base: # id
variableunica = str(info.get_attribute("outerText")
driver.quit()
return variableunica
问题就在这里。
id_base = driver.find_elements_by_xpath('//h3[@class="focus"]')
for info in id_base: # id
variableunica = str(info.get_attribute("outerText")
如果id_base
是一个空列表怎么办?
然后它从不循环通过下一行中的id_base
,并且variableunica
从不被分配任何值。然后你试着退货。
解决方案:
添加
variableunica = ""
在进入循环之前。