首页 > 解决方案 > BeautifulSoup - find_all - 返回空列表

问题描述

我正在尝试为 Udemy 的课程抓取网页。视频 334 现代 Python 3 训练营

我正在查看一个带有引号的页面,每个引用都有一个作者、ahref 和引用。我需要把这些都放在列表中。

.select_all 什么都不返回。如果我使用 .select 它可以工作,但是我不能“.find”我以后需要的东西,因为出现错误:AttributeError: 'list' object has no attribute 'find' (Why --> :*( >__> )

请在下面查看我的代码,并查看有效与无效之间的注释:

url = "http://quotes.toscrape.com"
url_next = "/page/1"
ori_url = requests.get(f"{url}{url_next}").text
every_thang = []

soup = BeautifulSoup(ori_url, "html.parser")
#all_the_quotes = soup.select(".quote") # this actually works, but cant use .find on it later
all_the_quotes2 = soup.find_all(".quote")

for q in all_the_quotes2:
    every_thang.append({
    "text": all_the_quotes2.find(".text").get_text(),
    "author": all_the_quotes2.find(".author").get_text(),
    "linky": all_the_quotes2.find("a")["href"]
    }) 

#for q in all_the_quotes: # gives error trying to use find
#    every_thang.append({
#    "text": all_the_quotes.find(".text").get_text(),
#    "author": all_the_quotes.find(".author").get_text(),
#    "linky": all_the_quotes.find("a")["href"]
#    }) 

print(all_the_quotes2)

标签: python-3.xbeautifulsoup

解决方案


使用 findAll 的正确方法是:

all_the_quotes2 = soup.find_all("div", {"class": "quote"})

推荐阅读