【问题标题】:Scrape content inside a form - BeautifulSoup在表单中抓取内容 - BeautifulSoup
【发布时间】:2017-10-12 13:08:01
【问题描述】:

我正在尝试使用 BeautifulSoup 和 Python 3.5 抓取像 this 这样的页面。具体来说,我对尺寸的数量感兴趣。在此特定页面中,尺寸数量为 3(S、M、L)。此信息可以在 html 代码的表单中找到。

我试过的代码是:

import requests
from bs4 import BeautifulSoup

page = requests.get('http://www.bendonlingerie.com.au/pleasure-state-d-arcy-delatour-soft-cup-bra-jester-red-p21-2346w')
soup=BeautifulSoup(page.content,'html.parser')
right = soup.find("div", class_="product-shop")
sizes = right.find("div", id="sizes")
sizes = sizes.find("ul", class_="button-size-list combo-list")
sizes = sizes.find_all("li")
nu_of_sizes = len(sizes)
print(nu_of_sizes)

此代码打印“0”。正确的打印应该是“3”,因为有 3 种尺寸(S、M、L)。我不想使用 selenium 或此类软件包。有没有办法使用 BeautifulSoup 来“捕捉”这些数据?

【问题讨论】:

  • 这个链接是 SFW 吗? :P

标签: python web-scraping beautifulsoup


【解决方案1】:

如果您仔细检查页面源,您会注意到您感兴趣的数据是json 格式(右键单击页面,查看页面源,然后搜索productJson)。因此,您可以检查它的开始位置和结束位置,并使用 json.loads() 将该切片反序列化为 Python 对象:

import requests
import json

page = requests.get('http://www.bendonlingerie.com.au/pleasure-state-d-arcy-delatour-soft-cup-bra-jester-red-p21-2346w')
content = page.text

start = content.find('productJson') + 13
end = content.find('function comboListClick') - 2

data = json.loads(content[start:end])

sizes = data['attributes']['172']['options']

print(len(sizes))

输出:

3

【讨论】:

  • 谢谢@mentalita。如何检查它的开始和结束位置?
  • @nesi:好吧,您必须手动检查页面源才能找到它。
猜你喜欢
  • 2020-09-06
  • 2015-01-05
  • 1970-01-01
  • 2019-06-28
  • 2020-09-28
  • 1970-01-01
  • 2022-08-18
  • 2020-10-24
相关资源
最近更新 更多