BeautifulSoup4 - AttributeError: 'NoneType' object has no attribute 'get_text'

BeautifulSoup4 - AttributeError: 'NoneType' object has no attribute 'get_text'

我是 BS4 的新手,我已经通读了所有类似的问题。我试图从一个句子中抓取一个数字,以便我可以遍历所有页面。这句话是“第 1 页,共 5 页”,我试图获取数字“5”并将其存储到一个变量中。但是,我遇到一个错误,指出 AttributeError: 'NoneType' object has no attribute 'get_text'。下面是 HTML:

这是我试过的代码。

    from bs4 import BeautifulSoup
    import requests
    
    url = 'https://www.edgeprop.my/buy/kelantan/all-residential?page=1'
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.79 Safari/537.36'}
    page = requests.get(url, headers=headers)
    
    soup = BeautifulSoup(page.content, 'html.parser')
    
    total_pages = soup.find('div', class_="tep-page-count").get_text()
    print(total_pages.strip())

我尝试过的一些试错解决方案是将 html.parser 替换为 lxml,替换 class 名称带有 text-centerlisting-colwavylisting -wrapper 两者都不起作用。

您在页面上看到的数据是通过 JavaScript 从外部 URL 加载的(因此 beautifulsoup 看不到它)。要获取找到的属性总数,您可以使用此示例:

import json
import requests

url = "https://www.edgeprop.my/jwdsonic/api/v1/property/search?=&listing_type=sale&state=Kelantan&property_type=rl&start=0&size=20"
data = requests.get(url).json()

# uncomment to print all data:
# print(json.dumps(data, indent=4))

print("Total number of properties found:", data["found"])

打印:

Total number of properties found: 84