如何在标记中获取文本<script>



我正在抓取LaneBryant网站。

部分源代码是

<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>

为了获得美元价格,我编写了这个脚本:

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]))

其中开始是 :

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

即使我得到正确的文本,它也不会打印价格。我如何获得价格?

在这种情况下,您可以只为价格提供正则表达式

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])

否则,请按 id 定位相应的脚本标记,然后使用 json 库解析 .text

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'})

这实际上是<script>标签,所以更好的名称是

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

您可以使用.text访问脚本标记中的文本。在这种情况下,这将为您提供 JSON。

json_string = script_tag.text

不要用逗号拆分,而是使用 JSON 解析器来避免误解:

import json    
clothing=json.loads(json_string)

相关内容

最新更新