使用Python从电子商务Ajax站点刮取JSON数据

问题描述 投票:3回答:3

以前,我发布了一个问题,我如何从这个链接获取AJAX网站的数据:Scraping AJAX e-commerce site using python

我对如何获得在网络选项卡中使用chrome F12并使用python进行编码以显示数据的响应有所了解。但我几乎找不到具体的API网址。 JSON数据不是来自之前网站的URL,而是来自Chrome F12中的Inspect Element。

enter image description here enter image description here


  1. 我真正的问题实际上是如何使用BeautifulSoup或与之相关的任何东西获取JSON数据?在我只能从application / id + json获取JSON数据后,我将其转换为python可识别的JSON数据,以便我可以将产品显示为表格形式。
  2. 还有一个问题是,经过几次运行代码后,JSON数据丢失了。我认为该网站将阻止我的IP地址。我该如何解决这个问题?

这是网站链接:

https://www.lazada.com.my/catalog/?_keyori=ss&from=input&page=1&q=h370m&sort=priceasc

这是我的代码

从bs4导入BeautifulSoup导入请求

page_link ='https://www.lazada.com.my/catalog/?_keyori=ss&from=input&page=1&q=h370m&sort=priceasc'

page_response = requests.get(page_link,timeout = 5)

page_content = BeautifulSoup(page_response.content,“html.parser”)

打印(PAGE_CONTENT)

python json ajax beautifulsoup response
3个回答
2
投票

你可以使用find方法和指向你的<script>标签的指针和attr type=application/json

然后你可以使用json包在dict中加载值

这是一个代码示例:

from bs4 import BeautifulSoup as soup
import requests
import json

page_link = 'https://www.lazada.com.my/catalog/?_keyori=ss&from=input&page=1&q=h370m&sort=priceasc'
page_response = requests.get(page_link, timeout=5)
page_content = soup(page_response.text, "html.parser")

json_tag = page_content.find('script',{'type':'application/json'})
json_text = json_tag.get_text()
json_dict = json.loads(json_text)
print(json_dict)

编辑:我的坏,我没有看到你搜索type=application/ld+json attr因为它似乎有几个<script>with这个attr,你可以简单地使用find_all方法:

from bs4 import BeautifulSoup as soup
import requests
import json

page_link = 'https://www.lazada.com.my/catalog/?_keyori=ss&from=input&page=1&q=h370m&sort=priceasc'
page_response = requests.get(page_link, timeout=5)
page_content = soup(page_response.text, "html.parser")

json_tags = page_content.find_all('script',{'type':'application/ld+json'})
for jtag in json_tags:
    json_text = jtag.get_text()
    json_dict = json.loads(json_text)
    print(json_dict)

1
投票

为什么不使用这个导入请求

response = requests.get(...)data = response.json()


1
投票

您将不得不从Soup手动解析HTML数据,因为其他网站将限制他们的json API来自其他方。

您可以在文档中找到更多详细信息:https://www.crummy.com/software/BeautifulSoup/bs4/doc/

© www.soinside.com 2019 - 2024. All rights reserved.