【问题标题】:Create list names dynamically from for loop从 for 循环动态创建列表名称
【发布时间】:2022-01-09 20:58:29
【问题描述】:

我正在尝试抓取 Goodreads 上选择奖中列出的书籍的描述。 我正在使用以下函数来获取为特定类型列出的各个 url

def get_genre_url(genre):    
    all_links = []

    for year in (range(2011,2022)):        
        url = 'https://www.goodreads.com/choiceawards/best-' + genre + '-books-'+ str(year)        
        page = requests.get(url) 
        soup = bs(page.content, 'html.parser') 
        for link in soup.find_all('a',  {'class':'pollAnswer__bookLink'}):                
            all_links.append('https://www.goodreads.com' + link.get('href'))
                
    return(all_links)

在获得书籍网址后,我会继续删除这些网址以获取书籍说明。

def get_description(genre_list):
    
    urls = []
    authors = []
    titles = []
    index = 0
    
    for url in genre_list:
        #print(index,url)

        page = requests.get(url)    
        soup = bs(page.content, 'html.parser')    

        authors.append(soup.find('title').get_text().split(' by ')[1])
        #print(index,authors)
        description_df = pd.DataFrame (authors, columns = ['author'])    

        titles.append(soup.find('title').get_text().split(' by ')[0])

        description_df['title'] = titles

        if soup.find('div',{'class':'readable stacked'}) is None:
            #print('This is a NoneType page:', url)
            description = soup.find('div',{'class':'TruncatedText__text TruncatedText__text--5'})
        else:
            description = soup.find('div',{'class':'readable stacked'}).get_text()
        urls.append(description)
        index += 1

        description_df['description'] = urls
        
    return(description_df)

为了获得我会调用的最终数据框(例如)

mystery_thriller_list = get_genre_url('mystery-thriller')
description_myster_thriller = get_description(mystery_thriller_list)

但是,我想要将流派列表(例如 genres = ['fiction', 'mystery-thriller'])传递到函数中,并为每个流派创建最终数据帧,其中数据框名称将具有命名约定 description_'selected 流派'。 到目前为止,我还没有弄明白,for 循环需要一些时间,因为它会为每种类型的 220 本书加载信息。

【问题讨论】:

    标签: python pandas list for-loop web-scraping


    【解决方案1】:

    您可以将所有数据帧存储在字典中,并将键作为它们的流派名称。

    all_genres_descriptions = {}    
    genres = ['fiction', 'mystery-thriller']
    for genre in genres:
        genre_list = get_genre_url(genre)
        description_genre = get_description(genre_list)
        all_genres_descriptions[f'description_{genre}'] = description_genre
    

    【讨论】:

      【解决方案2】:

      几件事。对于测试,您无需浏览所有年份和书籍。我只看一年和前两本书。要执行您正在寻找的操作,您可以使用 globals()。您可能还只想创建一个数据框,但在每次迭代中添加一列“流派”并连接。从长远来看,将所有数据放在一个数据框中可能会更容易。

      genres = ['fiction', 'mystery-thriller']
      for genre in genres:
          mystery_thriller_list = get_genre_url(genre)
          globals()[f"{genre.replace('-', '_')}_selected_genre"] = get_description(mystery_thriller_list)
      
      print(fiction_selected_genre)
      
      
      author  title   description
      0   Haruki Murakami 1Q84 (1Q84 #1-3)    \nThe year is 1984 and the city is Tokyo.A you...
      1   Sarah Addison Allen The Peach Keeper    \nThe New York Times bestselling author of The...
      
      print(mystery_thriller_selected_genre)
      
      
      author  title   description
      0   Janet Evanovich | Goodreads Smokin' Seventeen (Stephanie Plum, #17) [[[<p><b><i>Where there’s smoke there’s fire, ...
      1   J.D. Robb   New York to Dallas (In Death, #33)  \nTwelve years ago, Eve Dallas was just a rook...
      

      【讨论】:

        猜你喜欢
        • 2022-12-01
        • 2012-05-16
        • 1970-01-01
        • 2022-12-12
        • 2013-01-27
        • 1970-01-01
        • 2021-04-06
        • 2018-08-20
        • 1970-01-01
        相关资源
        最近更新 更多