python - 使用 Python 从电子商务 Ajax 站点抓取 JSON 数据

标签 python json ajax beautifulsoup response

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

我有点了解如何在“网络”选项卡中使用 chrome F12 获得响应,并使用 python 进行一些编码以显示数据。但我几乎找不到它的具体 API url。 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

这是我的代码

from bs4 import BeautifulSoup import requests

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

print(page_content)

最佳答案

您可以只使用 find使用指向您的 <script> 的指针的方法带有 attr 的标签 type=application/json

然后你可以使用json将值加载到字典中的包

这是一个代码示例:

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属性 因为它似乎有几个 <script>使用此属性,您可以简单地使用 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)

关于python - 使用 Python 从电子商务 Ajax 站点抓取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54781979/

相关文章:

java - Play 2 : Best way to deliver JSON content

json - 将 Firebase 实时数据库 json 响应从 _InternalLinkedHashMap<Object?, Object?> 转换为 Map<String,dynamic>

node.js - ( Node :7016) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated

c# - 在 ASP.NET 中重定向之前的 Javascript 警报

python - 在 pandas 数据框中寻找值(value)

Python/mysql : ProgrammingError: Not all parameters were used in the SQL statement

python - 消除 JSON 文档中键值的前导和尾随反冲

python - 使用 PyQT 使用 headless webkit 实现时,HTML 页面大不相同

python - Seaborn barplot 为色调添加 xticks

javascript - Ajax 仅将字符串化数组的第一个索引返回给 Spring Controller