源代码隐藏的值 - Webscraping Python

时间:2016-02-09 03:08:52

标签: javascript python html web-scraping beautifulsoup

我试图通过网络搜索网站,当我浏览源代码时,我所寻找的并不存在。网站是http://www.providentmetals.com/2016-1-oz-canadian-silver-cougar.html,我正在寻找的是右上角表格中的价格。它说" 1 +"其次是价格。它现在约为18.04美元。 当我"检查元素"使用Web开发人员工具,我可以看到价格。 使用BeautifulSoup我试图获得价值,但它并没有显示出来。这里的代码很粗糙。 它根本不会返回值

import res,bs4
url='http://www.providentmetals.com/2016-1-oz-canadian-silver.cougar.html'
res=requests.get(url)
soup=bs4.BeautifulSoup(res.text,'lxml')
elems=soup.findAll('class',{'table':'table table-striped border-light pricing data-table'})
#table name found from inspect element web dev tool

问题:如何找到隐藏数据?您知道使用bs4 / requests查找数据有什么方法吗?我不擅长编码和网页编写,所以任何帮助都会很好。

1 个答案:

答案 0 :(得分:0)

这些值不会被隐藏,它们是通过Ajax请求获得的,然后插入到页面的DOM中。这就是您在浏览器中看到它们的原因,而不是在网页的HTML中。

您可以直接访问获取所需数据的Ajax请求。响应采用JSON格式,因此非常易于使用。您需要知道SKU,例如,BBFS-04253。

网址是: http://www.providentmetals.com/services/products.php?type=product&sku=BBFS-04253

使用requests模块:

import requests

url = 'http://www.providentmetals.com/services/products.php'
params = {'type': 'product', 'sku': 'BBFS-04253'}
response = requests.get(url, params)
data = response.json()

>>> from pprint import pprint
>>> pprint(data)
[{u'as_low_as': {u'crypto_price': u'$18.22',
                 u'list_price': u'$18.78',
                 u'price': u'$18.03',
                 u'qty': 1,
                 u'to_tier': u' + '},
  u'crypto_price': u'$18.22',
  u'crypto_special_price': u'$0.00',
  u'id': u'6034',
  u'inStock': None,
  u'list_price': u'$18.78',
  u'list_special_price': u'$0.00',
  u'name': u'2016 1 oz Canadian Silver Cougar | Predator Series',
  u'price': u'$18.03',
  u'sell_to_us': u'$16.69',
  u'sku': u'BBFS-04253',
  u'special_price': None,
  u'status_allows_price': True,
  u'stock_status_code': u'pre-sale',
  u'tier_price': [{u'crypto_price': u'$18.22',
                   u'list_price': u'$18.78',
                   u'price': u'$18.03',
                   u'qty': 1,
                   u'to_tier': u' + '}]}]
    print data['price']

因此,您可以直接访问价格和其他详细信息:

>>> data[0]['price']
u'$18.03'
>>> data[0]['name']
u'2016 1 oz Canadian Silver Cougar | Predator Series'
相关问题