Python 无法刮取屏幕上不可见但属于滑块/转盘一部分的数据
我无法在作为滑块/旋转木马一部分的网站上刮取数据。当我运行脚本时,它只从滑块/旋转木马中刮取第一个项目。它不会遍历旋转木马中的所有页面 我试图浏览的网站是: 我的Python脚本:Python 无法刮取屏幕上不可见但属于滑块/转盘一部分的数据,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,我无法在作为滑块/旋转木马一部分的网站上刮取数据。当我运行脚本时,它只从滑块/旋转木马中刮取第一个项目。它不会遍历旋转木马中的所有页面 我试图浏览的网站是: 我的Python脚本: soup = BeautifulSoup(response, 'html.parser') divTag = soup.find_all("a", class_=['sc-VigVT', 'eJWBx']) for tag in divTag: tdTags = tag.find_all("h3", cl
soup = BeautifulSoup(response, 'html.parser')
divTag = soup.find_all("a", class_=['sc-VigVT', 'eJWBx'])
for tag in divTag:
tdTags = tag.find_all("h3", class_=['sc-jAaTju', 'iNsSAY'])
for tag in tdTags:
print(tag.text)
输出:
Kunal Bahl和Rohit Bansal揭示了Snapdeal转变的内幕
有7个旋转木马项目,但我只能得到第一个。我无法从转盘/滑块中的第2-7页获取数据
请查看我所指的下图(红色圆圈):
旋转木马是使用JS硬编码的JSON数据从Javascript生成的。确切地说,这个JSON是通过以下方式引入的:
window.__REDUX_STATE__= { ..... }
因此,据推测仅供参考,该网站用于管理应用程序的状态
我们可以使用以下脚本提取此JSON:
import requests
from bs4 import BeautifulSoup
import json
import pprint
r = requests.get('https://yourstory.com/')
prefix = "window.__REDUX_STATE__="
soup = BeautifulSoup(r.content, "html.parser")
#get the redux state (json)
data = [
json.loads(t.text[len(prefix):])
for t in soup.find_all('script')
if "__REDUX_STATE__" in t.text
]
#get only the section with cardType == "CarouselCard"
carouselCards = [
t["data"]
for t in data[0]["home"]["sections"]
if ("cardType" in t) and (t["cardType"] == "CarouselCard")
][0]
#print all cards
pprint.pprint(carouselCards)
#get the name, image path & link path
print([
(t["title"], t["path"], t["metadata"]["thumbnail"])
for t in carouselCards
])
JSON在home
字段中有一个sections
数组。此节对象包括一些具有值CarouselCard
的cardType
对象,其中包含您要查找的数据
另外,从JSON开始,Carousel部分如下所示:
{
"type":"content",
"dataAPI":"/api/v2/featured_stories?brand=yourstory&key=CURATED_SET",
"dataAttribute":"featured",
"cardType":"CarouselCard",
"data":[]
}
因此,我想您也可以使用API获取卡:
哪个更简单谢谢伯特朗的快速回复。API部分非常有用:)
import requests
r = requests.get('https://yourstory.com/api/v2/featured_stories?brand=yourstory&key=CURATED_SET')
#get the name, image path & link path
print([
(t["title"], t["path"], t["metadata"]["thumbnail"])
for t in r.json()["stories"]
])