简体   繁体   中英

How to get text within <script> tag

I am scraping the LaneBryant website .

Part of the source code is

<script type="application/ld+json">
{
"@context": "http://schema.org/",
"@type": "Product",
"name": "Flip Sequin Teach & Inspire Graphic Tee",
"image": [
"http://lanebryant.scene7.com/is/image/lanebryantProdATG/356861_0000015477",
"http://lanebryant.scene7.com/is/image/lanebryantProdATG/356861_0000015477_Back"
],
"description": "Get inspired with [...]",
"brand": "Lane Bryant",
"sku": "356861",
"offers": {
"@type": "Offer",
"url": "https://www.lanebryant.com/flip-sequin-teach-inspire-graphic-tee/prd-356861",
"priceCurrency": "USD",
"price":"44.95",
"availability": "http://schema.org/InStock",
"itemCondition": "https://schema.org/NewCondition"
}
}
}
}
</script>

In order to get price in USD, I have written this script:

 def getPrice(self,start):
            fprice=[]
            discount = ""


            price1 = start.find('script', {'type': 'application/ld+json'})
            data = ""
            #print("price 1 is + "+ str(price1)+"data is "+str(data))
            price1 = str(price1).split(",")
            #price1=str(price1).split(":")
            print("final price +"+ str(price1[11]))

where start is :

        d = webdriver.Chrome('/Users/fatima.arshad/Downloads/chromedriver')
        d.get(url)
        start = BeautifulSoup(d.page_source, 'html.parser')

It doesn't print the price even though I am getting correct text. How do I get just the price?

In this instance you can just regex for the price

import requests, re

r = requests.get('https://www.lanebryant.com/flip-sequin-teach-inspire-graphic-tee/prd-356861#color/0000015477', headers = {'User-Agent':'Mozilla/5.0'})
p = re.compile(r'"price":"(.*?)"')
print(p.findall(r.text)[0])

Otherwise, target the appropriate script tag by id and then parse the .text with json library

import requests, json
from bs4 import BeautifulSoup 

r = requests.get('https://www.lanebryant.com/flip-sequin-teach-inspire-graphic-tee/prd-356861#color/0000015477', headers = {'User-Agent':'Mozilla/5.0'})
start = BeautifulSoup(r.text, 'html.parser')
data = json.loads(start.select_one('#pdpInitialData').text)
price = data['pdpDetail']['product'][0]['price_range']['sale_price']
print(price)
price1 = start.find('script', {'type': 'application/ld+json'})

This is actually the <script> tag, so a better name would be

script_tag = start.find('script', {'type': 'application/ld+json'})

You can access the text inside the script tag using .text . That will give you the JSON in this case.

json_string = script_tag.text

Instead of splitting by commas, use a JSON parser to avoid misinterpretations:

import json    
clothing=json.loads(json_string)

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