【问题标题】:Extract Data From Script Tag从脚本标签中提取数据
【发布时间】:2020-06-18 05:10:56
【问题描述】:

我正在尝试从ecommerce 网站上抓取一些属性 但数据不存储在 html 中,它存储在 javascript script 标签中

我正在尝试从script 标签获取productId,product,brand

import requests
from bs4 import BeautifulSoup

base_url = "https://www.myntra.com/men-formal-shirts?f=Collar%3AButton-Down%20Collar"

r = requests.get(base_url)

soup = BeautifulSoup(r.text, 'html.parser')

scripts = soup.find_all('script')[8]
scripts

【问题讨论】:

  • 到底是什么问题?你有没有尝试过,做过任何研究?你甚至没有分享数据的实际样子。

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:
import requests
from bs4 import BeautifulSoup
import json
import pyjsparser

r = requests.get(
    "https://www.myntra.com/men-formal-shirts?f=Collar%3AButton-Down%20Collar&p=1")

soup = BeautifulSoup(r.text, 'html.parser')

script = soup.findAll("script")[8].text

tree = pyjsparser.parse(script)

print(tree.keys())

【讨论】:

  • @chitown88 是的,这对我们俩来说都是新的:D stackoverflow.com/questions/60520118/… 昨天正在研究它。这是使用它的第二天。
  • @chitown88 @αԋɱҽԃαмєяιcαη pyjsparser 对我来说也很新:D 我已经安装了它,看看它能做什么。顺便说一句:今天我还看到 js2xml 将 JavaScript 解析为 XML ETree 并可以使用 xpath 来搜索元素。
  • @furas 很高兴见到你。你的博客昨天在审查后为我解决了一个更大的问题。 decode issue 干得好。我已经报告了 10 天以来在 github 上的请求团队也
  • 很高兴听到这个博客有时很有用。在question with this problem 之后,我也想举报。但最后我辞职了。我只遇到过一两次这个问题,所以它不是经常出现的问题。
  • @furas 这通常发生在 Windows 用户身上。
【解决方案2】:

您可以将script 设为text 并从开头删除window.__myx =,您将获得正确的JSON 数据,您可以使用标准模块json 将其转换为Python 的字典。

然后你可以使用keysfor-loop来获取信息

import requests
from bs4 import BeautifulSoup
import json

base_url = "https://www.myntra.com/men-formal-shirts?f=Collar%3AButton-Down%20Collar"

r = requests.get(base_url)

soup = BeautifulSoup(r.text, 'html.parser')

# get .text
scripts = soup.find_all('script')[8].text

# remove window.__myx = 
script = scripts.split('=', 1)[1]

# convert to dictionary
data = json.loads(script)

for item in data['searchData']['results']['products']:
    print('product:', item['product'])
    print('productId:', item['productId'])
    print('brand:', item['brand'])
    print('---')

结果:

product: Louis Philippe Men White & Blue Slim Fit Checked Formal Shirt
productId: 11390900
brand: Louis Philippe
---
product: Hancock Men White Slim Fit Solid Formal Shirt
productId: 7460073
brand: Hancock
---
product: INVICTUS Men Navy Slim Fit Printed Semiformal Shirt
productId: 6970620
brand: INVICTUS
---
product: next Men White Slim Fit Solid Formal Shirt
productId: 11067410
brand: next
---
product: INVICTUS Men White & Green Slim Fit Printed Semiformal Shirt
productId: 2314014
brand: INVICTUS
---
product: Dazzio Men Black Modern Slim Fit Solid Formal Shirt
productId: 3009355
brand: Dazzio
---

etc.

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 2020-02-19
    • 2020-01-07
    • 2020-12-07
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多