Python我如何使用bs4a javascript代码?

2024-09-20 06:55:49 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在尝试从一个html中提取一个javascript值。代码中有很多javascript,但我只想打印出这个:

var spConfig=newProduct.Config({
  "attributes": {
    "531": {
      "id": "531",
      "options": [
        {
          "id": "18",
          "hunter": "0",
          "products": [
            "128709"
          ]
        },
        {
          "label": "40 1\/2",
          "hunter": "0",
          "products": [
            "120151"
          ]
        },
        {
          "id": "33",
          "hunter": "0",
          "products": [
            "120152"
          ]
        },
        {
          "id": "36",
          "hunter": "0",
          "products": [
            "128710"
          ]
        },
        {
          "id": "42",
          "hunter": "0",
          "products": [
            "125490"
          ]
        }
      ]
    }
  },

  "Id": "120153",

});

所以我先做了一个代码,看起来像:

^{pr2}$

我得到的输出非常巨大,所以我不能在这里全部发布,但是其中一个是我在顶部提到的javascript,我只想打印出var spConfig=newProduct.Config。在

我如何才能做到这一点,以便能够打印出var spConfig=newProduct.Config....供以后使用json.loads把它转换成一个json,以后我可以更容易地抓取它?在

对于我没有解释清楚的任何问题或事情。我会通知所有的评论,在这里我可以提高我自己在这里stackoverflow!:)

编辑:

关于bs4为javascripts输出的更多示例

<script type="text/javascript">varoptionsPrice=newProduct.Options({
  "priceFormat": {
    "pattern": "%s\u00a0\u20ac",
    "precision": 2,
    "requiredPrecision": 2,
    "decimalSymbol": ",",
    "groupSymbol": "\u00a0",
    "groupLength": 3,
    "integerRequired": 1
  },
  "showBoths": false,
  "idSuffix": "_clone",
  "skipCalculate": 1,
  "defaultTax": 20,
  "currentTax": 20,
  "tierPrices": [

  ],
  "tierPricesInclTax": [

  ],
  "swatchPrices": null
});</script>,
<script type="text/javascript">var spConfig=newProduct.Config({
  "attributes": {
    "531": {
      "id": "531",
      "options": [
        {
          "id": "18",
          "hunter": "0",
          "products": [
            "128709"
          ]
        },
        {
          "label": "40 1\/2",
          "hunter": "0",
          "products": [
            "120151"
          ]
        },
        {
          "id": "33",
          "hunter": "0",
          "products": [
            "120152"
          ]
        },
        {
          "id": "36",
          "hunter": "0",
          "products": [
            "128710"
          ]
        },
        {
          "id": "42",
          "hunter": "0",
          "products": [
            "125490"
          ]
        }
      ]
    }
  },

  "Id": "120153"
});</script>,
<scripttype="text/javascript">document.observe('dom:loaded',
function(){
  varswatchesConfig=newProduct.ConfigurableSwatches(spConfig);
});</script>

编辑更新2:

try:
    product_li_tags = bs4.find_all('script', {'type': 'text/javascript'})
except Exception:
    product_li_tags = []


for product_li_tag in product_li_tags:
   try:
        pat = "product.Config\((.+)\);"
        json_str = re.search(pat, product_li_tag, flags=re.DOTALL).group(1)
        print(json_str)
   except:
       pass

#json.loads(json_str)
print("Nothing")
sys.exit()

Tags: textidconfigjsonvartypetagsscript
2条回答

您可以使用.text函数来获取每个标记中的内容。然后,如果您知道要获取以“varoptionsPrice”开头的代码,则可以对其进行筛选:

soup = BeautifulSoup(myhtml, 'lxml')

script_blocks = soup.find_all('script', {'type': 'text/javascript'})
special_code = ''
for s in script_blocks:
    if s.text.strip().startswith('varOptionsPrice'):
        special_code = s.text
        break

print(special_code)

编辑:为了在评论中回答您的问题,有两种不同的方法来提取具有JSON的文本部分。您可以通过regexp传递它来获取第一个左括号之间和末尾的);之前的所有内容。不过,如果要完全避免regexp,可以执行以下操作:

^{pr2}$

然后用它制作一本有用的词典:

import json
j = json.loads(json_stuff)
print(j['defaultTax'])  # This should return a value of 20

我可以想出三个可能的选择-你使用哪一个可能取决于项目的规模和你需要它有多灵活

  • 使用Regex从脚本中提取对象(最快,最不灵活)

  • 使用ANTLR或类似的(例如pyjsparser)来解析js语法

  • 使用Selenium或其他无头浏览器可以为您解释JS。通过这个选项,您可以使用selenium执行一个调用来获取变量like this

正则表达式示例(#1)

>>> script_body = """
    var x=product.Config({
        "key": {"a":1}
});
"""
>>> pat = "product.Config\((.+)\);"
>>> json_str = re.search(pat, script_body, flags=re.DOTALL).group(1)
>>> json.loads(json_str)
{'key': {'a': 1}}
>>> json.loads(json_str)['key']['a']
1

相关问题 更多 >