首页 > 解决方案 > 用 Beautiful Soup 刮取宠物收养网站

问题描述

在尝试使用 python 和 Beautiful Soup 抓取详细信息时,我无法div在此网站上获取每个宠物的信息:https : //indyhumane.org/adoptable-cats/

当我检查页面并检查 html 源代码时,我看到div包含每个宠物配置文件的内容都带有class = "mbcpp_result_animal",但是当我使用下面的代码时,我的长度为零containers

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://indyhumane.org/adoptable-cats/'

uClient = uReq(my_url)

page_html = uClient.read()

uClient.close()

page_soup = soup(page_html, "html.parser")

containers = page_soup.findAll("div",{"class":"mbcpp_result_animal"})

print(len(containers))

如果我 print page_soup.body,当我在 chrome 的开发人员工具中检查页面时,我看不到任何与class="mbcpp_result_animal"html 源代码不同的 div 。

这是我的第一次网络抓取。所以,我觉得我还没有完全理解这个过程。谁能告诉我我需要做什么来解决这个问题?

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


因为这来自页面为检索结果和更新页面而进行的额外 API 调用。该调用具有查询字符串参数,您可以看到如下。

它包括 API 端点、api 密钥、限制搜索的条件和最终的随机数参数,大概是为了避免提供缓存结果。您可以引入一个实际的随机数。

import requests

r = requests.get('https://indyhumane.org/wp-content/plugins/mbc-petpoint/mbc-petpoint-data.php?species_name=cats&sex=A&ageGroup=All&orderBy=ID&primaryBreed=All&secondaryBreed=All&specialNeeds=A&api_key=14j14u8qzj27aqw6tv53k553lxcjff0xf2uh16i61t4s61g727&num_items=-1&apimode=AdoptableSearch&location=&rnd=1')
r.json()

推荐阅读