【发布时间】: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