以前,我发布了一个问题,我如何从这个链接获取AJAX网站的数据:Scraping AJAX e-commerce site using python
我对如何获得在网络选项卡中使用chrome F12并使用python进行编码以显示数据的响应有所了解。但我几乎找不到具体的API网址。 JSON数据不是来自之前网站的URL,而是来自Chrome F12中的Inspect Element。
这是网站链接:
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)
你可以使用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)
为什么不使用这个导入请求
response = requests.get(...)data = response.json()
您将不得不从Soup
手动解析HTML数据,因为其他网站将限制他们的json API
来自其他方。
您可以在文档中找到更多详细信息:https://www.crummy.com/software/BeautifulSoup/bs4/doc/