【发布时间】:2021-03-20 07:34:45
【问题描述】:
目前正尝试从网站抓取一些数据,我恢复了我需要存储的变量。例如:日期、作者、喜欢、不喜欢、浏览量...
我正在使用 BeautifulSoup4,这是我目前所处的状态:
try:
author = soup.find("div", {"class":"publish_info"}).find("a").text
date = soup.find("div", {"class":"created_at"}).find("div").text
views = soup.find("span", {"class":"views"}).text
likes = soup.find("button", {"class":"wrapper__text_button auto__app_page_body_upvote_button upvote_button_component"}).find("span", {"class":"count label"}).text
dislikes = soup.find("button", {"class":"wrapper__text_button auto__app_page_body_downvote_button downvote_button_component"}).find("span", {"class":"count label"}).text
df.loc[len(df)] = [title] + [author] + [date] + [views] + [likes] + [dislikes] + [nb] + [url] + [docurl]
except:
df.loc[len(df)] = [title] + ['unk'] + ['unk'] + ['unk'] + ['unk'] + ['unk'] + [nb] + [url] + [docurl]
我尝试通过查看我想要的 div 来获取 BS4 的所有变量,但如果一个失败,我不会得到任何其他变量。 有时,网站上只有一个不存在,但其他存在。这意味着我无法恢复所有变量。 我想要得到所有东西的想法是为每一个变量做一个 try 块,但这也太可怕了。我应该使用什么?目标是从网站中获取尽可能多的变量,以便使用 pandas 将它们输入到 DataFrame (df) 中。
【问题讨论】: