使用Python及bs4库提取网页名言列表与总页数遇到问题
问题解决方法
你当前代码的问题是:调用findAll()匹配id为quotesList的div时,findAll()会返回所有符合条件的元素组成的列表,而该id在页面中唯一存在,直接用find()获取单个元素即可。
以下是完整实现代码,包含名言提取存列表、底部总页数提取的功能:
from urllib.request import Request, urlopen from bs4 import BeautifulSoup as soup listOfQuotes = [] website = "https://www.brainyquote.com/authors/nassim-nicholas-taleb-quotes" req = Request(website, headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).read() s = soup(webpage,"html.parser") # 修正:用find获取单个quotesList容器 div_container = s.find("div", {"id":"quotesList"}) # 提取当前页所有名言存入列表 quote_items = div_container.find_all("div", class_="q-item") for item in quote_items: quote_text = item.find("a", class_="b-qt").get_text(strip=True) listOfQuotes.append(quote_text) # 提取页面底部总页数 pagination = s.find("ul", class_="pagination") if pagination: page_items = pagination.find_all("li", class_="page-item") # 分页栏倒数第二个元素对应最后一页页码(最后一个为下一页按钮) total_page = int(page_items[-2].get_text(strip=True)) print(f"该作者名言总页数:{total_page}") print(f"当前页提取到的名言数量:{len(listOfQuotes)}")
如果需要爬取所有页的名言,按页码规则拼接请求地址循环爬取即可,该网站作者名言分页地址规则为原地址后加_页码,比如第二页地址为https://www.brainyquote.com/authors/nassim-nicholas-taleb-quotes_2。
内容的提问来源于stack exchange,提问作者steve238
相关产品推荐
相关产品推荐

