我正在尝试使用
beautifulsoup
来做一个网络抓取项目。下面是代码。
from bs4 import BeautifulSoup
import requests
url = 'https://www.morphmarket.com/us/c/reptiles/pythons/ball-pythons/1419690'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
snakes = soup.find("div", class_ = "container--N6XSR")
print(snakes)
我能够提取 HTML;然而,当我打印“snakes”时,结果总是
None
,我不明白为什么。如果有人可以提供帮助,我们将不胜感激。
您无法找到该元素,因为内容是从 API 加载并动态呈现的。如果您不想使用可以像浏览器一样处理它的
selenium
,则必须直接通过API使用requests
获取数据并获得结构良好的JSON:
import requests
data = requests.get('https://www.morphmarket.com/api/v1/listings/1419690/').json()
JSON 中有很多信息,要获取这些信息进行购买,只需像使用
data
一样使用 dict
并选择所需信息:
data.get('purchase_details')
结果:
{'order_details': None,
'blocking_details': {'buyer_user_is_blocked_by_seller': None,
'seller_user_is_blocked_by_buyer': None,
'buyer_store_is_blocked_by_seller': None,
'seller_store_is_blocked_by_buyer': None},
'shipping_type': 'free_shipping',
'shipping_price': 0.0,
'shipping_price_display': '$0',
'purchase_preventing_reasons_list': ['Buyer should be authenticated'],
'seller_name': 'davegreen',
'inquiry_message': None,
'title': 'Cinnamon Special Het Monsoon Male',
'price': 2000.0,
'price_display': '$2,000',
'price_currency': '$'}