【问题标题】:To use Regex or not, to grab json value from a HTML是否使用正则表达式,从 HTML 中获取 json 值
【发布时间】:2019-12-19 07:48:42
【问题描述】:

所以我在这里得到了一些不同的答案。是否使用正则表达式运行。

我想要做的是我试图在 html 中获取一个特定值(spConfig 的 json),即:

<script type="text/x-magento-init">
        {
            "#product_addtocart_form": {
                "configurable": {
                    "spConfig": {"attributes":{"93":{"id":"93","code":"color","label":"Color","options":[{"id":"8243","label":"Helloworld","products":["97460","97459"]}],"position":"0"},"148":{"id":"148","code":"codish","label":"Codish","options":[{"id":"4707","label":"12.5","products":[]},{"id":"2724","label":"13","products":[]},{"id":"4708","label":"13.5","products":[]}],"position":"1"}},"template":"EUR <%- data.price %>","optionPrices":{"97459":{"oldPrice":{"amount":121},"basePrice":{"amount":121},"finalPrice":{"amount":121},"tierPrices":[]}},"prices":{"oldPrice":{"amount":"121"},"basePrice":{"amount":"121"},"finalPrice":{"amount":"121"}},"productId":"97468","chooseText":"Choose an Option...","images":[],"index":[]},
                    "gallerySwitchStrategy": "replace"
                }
            }
        }
    </script>

这就是问题所在。抓取 HTML 时,有多个 &lt;script type="text/x-magento-init"&gt;,但只有一个 spConfig,我这里有两个问题。

  1. 我是否应该使用 Regex 获取值 spConfig 以便以后使用 json.loads(spConfigValue)?如果不是,那么我应该使用什么方法来抓取 json 值?

  2. 如果我应该使用正则表达式。我一直在尝试使用\"spConfig\"\: (.*?) 来抓取它,但它并没有为我抓取 json 值。我做错了什么?

【问题讨论】:

  • 您在使用 BeautifulSoup 吗?还是您从 Splash 或使用 Selenium 无头刮取的动态加载的 javascript?如果用汤:stackoverflow.com/questions/26192727/…
  • @mgrollins 抱歉没有提及!我正在使用 BeautifulSoup bs4 = soup(requests.text, 'html.parser'),后来我使用 for values in bs4.find_all('script', {'type': 'text/x-magento-init'}):
  • 好的,太好了!检查该答案,看起来您可以通过负载将values 转换为json:data = json.loads(values.text),然后测试spConfig 是否是数据中的键,然后使用属性。
  • @mgrollins Yupp 我做到了 :) 但是现在我在获取正确的 .items() 值时遇到了问题,但这个问题不适合这里,因为这是别的东西:)
  • 我会用 json 加载它,然后使用 Try/Catch 访问正确的脚本标签,如果还没有新标签,我会输入一些内容作为答案。

标签: python json regex


【解决方案1】:

不,永远不要对 HTML 使用正则表达式。请改用 BeautifulSoup 之类的 HTML 解析器!

【讨论】:

  • 对!嗯,问题是在这种情况下,如果有任何建议 &lt;script type="text/x-magento-init"&gt; 的多个值,我将如何获取该值,因为问题是我没有想法哈哈。
【解决方案2】:

所以基本上对于 json 使用 json parser 是对的。 ? ? 对于 yaml 使用 yamel 解析器 ? 所以在 HTML 中使用 HTML 解析器 看一些例子,也喜欢这样会让你的生活发光

从 html.parser 导入 HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)

   def handle_endtag(self, tag):
      print("Encountered an end tag :", tag)

  def handle_data(self, data):
      print("Encountered some data  :", data)

 parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
        '<body><h1>Parse me!</h1></body></html>')

https://docs.python.org/3/library/html.parser.html

【讨论】:

    【解决方案3】:

    在这种情况下,bs4 4.7.1 + :contains 是你的朋友。您说只有一个匹配项,因此您可以执行以下操作:

    from bs4 import BeautifulSoup as bs
    import json
    
    html= '''<html>
     <head>
      <script type="text/x-magento-init">
            {
                "#product_addtocart_form": {
                    "configurable": {
                        "spConfig": {"attributes":{"93":{"id":"93","code":"color","label":"Color","options":[{"id":"8243","label":"Helloworld","products":["97460","97459"]}],"position":"0"},"148":{"id":"148","code":"codish","label":"Codish","options":[{"id":"4707","label":"12.5","products":[]},{"id":"2724","label":"13","products":[]},{"id":"4708","label":"13.5","products":[]}],"position":"1"}},"template":"EUR <%- data.price %>","optionPrices":{"97459":{"oldPrice":{"amount":121},"basePrice":{"amount":121},"finalPrice":{"amount":121},"tierPrices":[]}},"prices":{"oldPrice":{"amount":"121"},"basePrice":{"amount":"121"},"finalPrice":{"amount":"121"}},"productId":"97468","chooseText":"Choose an Option...","images":[],"index":[]},
                        "gallerySwitchStrategy": "replace"
                    }
                }
            }
        </script>
     </head>
     <body></body>
    </html>'''
    soup = bs(html, 'html.parser')
    data = json.loads(soup.select_one('script:contains(spConfig)').text)
    

    那么配置是:

    data['#product_addtocart_form']['configurable']['spConfig']
    

    带钥匙:

    【讨论】:

    • 太棒了!正是我在这里寻找的!欣赏它,这似乎比我想象的要容易得多!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多