简体   繁体   中英

Parse string to get href given attribute value

I have a string with the following content:

var string = 
'<div class="product-info-inner-content clearfix ">\
    <a href="http://www.adidas.co.uk/ace-17_-purecontrol-firm-ground-boots/BB4314.html"\
      class="link-BB4314 product-link clearfix "\
      data-context="name:ACE 17+ Purecontrol Firm Ground Boots"\
      data-track="BB4314"\
      data-productname="ACE 17+ Purecontrol Firm Ground Boots"  tabindex="-1">\
        <span class="title">ACE 17+ Purecontrol Firm Ground Boots</span>\
        <span class="subtitle">Men Football</span>\
    </a>\
</div>';

I am trying to perform the JavaScript equivalent of the following Python code, in which uses beautiful soup to grab the URL of the div class element given a product code (ie in this case BB4314).

 is_listing = len(soup.findAll(name="div", attrs={"class": "product-tile"})) > 1
        if is_listing:
        # stuck from this part
        attrs = {"class": re.compile(r".*\bproduct-link\b.*"), "data-track": code} 
        url = soup.find(name="a", attrs=attrs)
        url = url["href"]

How can I do this?

Just use DOM

 var string = '<div class="product-info-inner-content clearfix "><a href="http://www.adidas.co.uk/ace-17_-purecontrol-firm-ground-boots/BB4314.html" class="link-BB4314 product-link clearfix " data-context="name:ACE 17+ Purecontrol Firm Ground Boots" data-track="BB4314" data-productname="ACE 17+ Purecontrol Firm Ground Boots" tabindex="-1"><span class="title">ACE 17+ Purecontrol Firm Ground Boots</span> <span class="subtitle">Men Football</span></a></div>', div = document.createElement("div"); div.innerHTML = string; var href = div.querySelector("a.product-link").href, parts = href.split("/"), code = parts.pop().split(".")[0]; console.log(code) console.log(div.querySelector("a.product-link").getAttribute("data-track")) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM