【问题标题】:Parsing HTML With Complex Structure Using Beautiful Soup使用 Beautiful Soup 解析结构复杂的 HTML
【发布时间】:2021-04-06 13:34:00
【问题描述】:

抱歉,对于 noob html 抓取问题,但我正在处理复杂的 html,并且每种情况都是独一无二的。

我正在尝试解析所有前面的 URL:{"actionType":"navigate","actionUrl":

在下面的示例中,它将是 https://www.ABCD.com

我正在使用 python。最好是漂亮的汤。关于如何处理的想法?

</a>
<a aria-label="ABCD." class="we-lockup targeted-link l-column small-2 medium-3 large-2 we-lockup--shelf-align-top ember-view" data-metrics-click='{"actionType":"navigate","actionUrl":"https://www.ABCD.com","targetType":"card","targetId":"12345"}' data-metrics-location='{"locationType":"shelfCustomersAlsoBoughtMovie"}' href="https://www.ABCD.com" id="ember123"> <picture class="we-lockup__artwork we-artwork--lockup we-artwork--fullwidth we-artwork--vhs-movie-pic we-artwork ember-view" dir="ltr" id="ember123">
<noscript>

【问题讨论】:

    标签: python web-scraping beautifulsoup html-parsing


    【解决方案1】:

    您可以使用内置的 json 模块将数据转换为 Python 字典 (dict),然后访问 actionUrl 键。

    import json
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(html, "html.parser")
    
    data = soup.find(
        class_=
        'we-lockup targeted-link l-column small-2 medium-3 large-2 we-lockup--shelf-align-top ember-view'
    )['data-metrics-click']
    
    json_data = json.loads(data)
    
    print(type(json_data))
    print(json_data['actionUrl'])
    

    输出:

    <class 'dict'>
    https://www.ABCD.com
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2019-07-03
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多