简体   繁体   English

蟒蛇/硒。 列表未填满 IMDb href

[英]Python/Selenium. List is not filling up with IMDb hrefs

Hi I'm trying to piece together something that scrapes the hrefs from these 4 IMDb links but my list = [] won't seek to fill up even though when I return or print instead of append I get the list.嗨,我正在尝试拼凑一些从这 4 个 IMDb 链接中刮取 href 的东西,但我的 list = [] 不会试图填满,即使我返回或打印而不是 append 我得到了列表。 It worked before but maybe I moved something now it won't work.它以前工作过,但也许我现在移动了一些东西它不起作用。

first_page = 'https://www.imdb.com/title/'+movie+'/episodes?season=1'
second_page = 'https://www.imdb.com/title/'+movie+'/episodes?season=2'
third_page = 'https://www.imdb.com/title/'+movie+'/episodes?season=3'
fourth_page = 'https://www.imdb.com/title/'+movie+'/episodes?season=4'
driver.get(first_page)
driver.execute_script("window.open('" + second_page +"');") 
driver.execute_script("window.open('" + third_page +"');") 
driver.execute_script("window.open('" + fourth_page +"');") 
time.sleep(3)

# Handles is a variable which handles the 
handles = driver.window_handles
# Loops through each tab and performs a function
for handle in handles:
    driver.switch_to.window(handle)
    # Scrapes all hrefs(including episode links) builds a list
    links = []
    elements = driver.find_elements_by_tag_name('a')
    for elem in elements:
        href = elem.get_attribute("href")
        links.append(href)

time.sleep(5)

driver.quit()

This is the error NameError: name 'links' is not defined这是错误 NameError: name 'links' is not defined

As Robert Kovacs stated this is the answer.正如罗伯特·科瓦奇所说,这就是答案。

links = []
# Handles is a variable which handles the 
handles = driver.window_handles
# Loops through each tab and performs a function
for handle in handles:
    driver.switch_to.window(handle)
    # Scrapes all hrefs(including episode links) builds a list

    elements = driver.find_elements_by_tag_name('a')
    for elem in elements:
       href = elem.get_attribute("href")
       if href is not None:
        links.append(href)

time.sleep(5)

driver.quit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM