抓取隐藏数据 [ window.__WEB_CONTEXT__= ] ...最好使用 Scrapy

2024-02-09

我正在爬到到网。我现在的问题是抓取给定酒店的 Hotelstars(不是平均用户评级 [bubbles],而是酒店等级评级),稍后我将遇到隐藏在“阅读更多”后面的评论问题。https://www.tripadvisor.com.ph/Hotel_Review-g8762949-d1085145-Reviews-El_Rio_y_Mar_Resort-San_Jose_Coron_Busuanga_Island_Palawan_Province_Mimaropa.html https://www.tripadvisor.com.ph/Hotel_Review-g8762949-d1085145-Reviews-El_Rio_y_Mar_Resort-San_Jose_Coron_Busuanga_Island_Palawan_Province_Mimaropa.html幸运的是我知道在哪里可以找到这两个数据。它在该标签内的页面中:

<script window.__WEB_CONTEXT={pageManifest:{"assets":[.... 
....
</script>

在这里搜索https://pastebin.com/Ww3ugxFR https://pastebin.com/Ww3ugxFR因为“景色太棒了!!” (隐藏文本示例)或“星级”:酒店之星。

我想了解如何访问此标签。

这是我的例子,说明它是如何不起作用的。我需要学习如何告诉 CSS 选择器(或其他工具)如何解决这个特定问题以及如何从中提取数据。在此示例中,我将仅加载响应并进行简单的模式搜索。我想人们也可以用 Json 加载它并从那里提取,但我还没有用 Json 来确定。:

hotel_CONTEXT = response.css("script text=window.__WEB_CONTEXT ::attr(pageManifest)).extract()

pattern_hotelstar = re.compile(r'star":\["\d')
matches_hotelstar = pattern_hotelstar.findall(hotel_CONTEXT)
Hotel_stars = str(matches_hotelstar).split('"')[2].split("'")[0]

显然我想要实现的目标可以通过 BeautifulSoup 实现(抓取隐藏在“阅读更多”下的数据的网站 https://stackoverflow.com/questions/56682371/scraping-a-website-with-data-hidden-under-read-more...但是我在尝试复制时遇到了 json 错误)但通常我更喜欢使用 Scrapy 的解决方案。


Andrej Kesely 提供了一个出色的解决方案我的问题!他的代码运行得非常好,我想完全理解它!这是我认为从代码中可以理解的内容,而我只是不明白他的魔法;):

data = re.search(r'window\.__WEB_CONTEXT__=(.*?});', html_text).group(1)

Andrej 在整个 html_text 中搜索以“window.__WEB...”开头的模式,以非贪婪方式 (?) 将模式扩展到所有字符 (.) 任意次数 (*),并以我不明白为什么有一个带有 } init 的捕获组,以及为什么 } 不只是放在最后,因为脚本以 }; 结尾。 (安德烈是如何发现这一点的?这是这些的一般模式还是他打印了整页并查找了它?)。我也不明白为什么它必须是非贪婪的。 Group(1) 选择了第一个括号内的所有内容,留下了窗口。WEB_CONTEXT= 出来。我猜这与使用 json 加载结果有关。同样适用于

data = data.replace('pageManifest', '"pageManifest"')   

然后 Andrej 创建一个名为 traverse 的函数,稍后将用数据的输出填充该函数。在 if 语句中,Andrej 检查输入是否是字典。在下一步中,Andrej 循环遍历字典的 key(k) 和 value(v)。如果 k==“评论”,他就会产生该值。如果不是“函数的产量”?我也迷失了 elif 和检查 val 是否是一个列表...一般来说,函数的输出 v 是什么?我将如何更改该函数以包含更多要滚动的字典,因为 else 已被此收益占据。

def traverse(val):
if isinstance(val, dict):
    for k, v in val.items():
        if k == 'reviews':
            yield v
        else:
            yield from traverse(v)
elif isinstance(val, list):
    for v in val:
        yield from traverse(v)
 

这里 Andrej 循环遍历 traverse(data)(字典,对吧?)。由于我们在此页面上收到了多条评论。 在嵌套循环中,Andrej 为单个评论中的每个字典指定名称 r,并通过 dictonary_name["key"] 检索存储的值。我对吗 ?

for reviews in traverse(data):
  for r in reviews:
    print(r['userProfile']['displayName'])
    print(r['title'])
    print(r['text'])
    print('Rating:', r['rating'])
    print('-' * 80)

很抱歉提出所有这些菜鸟问题。


该脚本将打印页面上找到的所有评论和评论评级:

import re
import json
import requests


url = 'https://www.tripadvisor.com.ph/Hotel_Review-g8762949-d1085145-Reviews-El_Rio_y_Mar_Resort-San_Jose_Coron_Busuanga_Island_Palawan_Province_Mimaropa.html'
html_text = requests.get(url).text

data = re.search(r'window\.__WEB_CONTEXT__=(.*?});', html_text).group(1)
data = data.replace('pageManifest', '"pageManifest"')
data = json.loads(data)

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

def traverse(val):
    if isinstance(val, dict):
        for k, v in val.items():
            if k == 'reviews':
                yield v
            else:
                yield from traverse(v)
    elif isinstance(val, list):
        for v in val:
            yield from traverse(v)

for reviews in traverse(data):
    for r in reviews:
        print(r['userProfile']['displayName'])
        print(r['title'])
        print(r['text'])
        print('Rating:', r['rating'])
        print('-' * 80)

Prints:

BBDoll619
Just WOW!!
Okay, I didn't know this resort would be mainly couples and honeymooners as I went with 2 friends. We weren't uncomfortable though and met lots of nice people from across the globe and 1 couple from the US. This resort can only be reached by boat, so it is very secluded. We stayed in bungalow #2. It was rustic, but beautiful and right on the beach. Everyone who worked in the resort was friendly and very accommodating. We ate most meals at the resort which was pretty good. We had happy hour at the pier bar every day which was from 4-7pm. They had half off certain drinks and food specials. It was very nice relaxing, enjoying a great drink and watching the sunset. You can snorkel right in front of the resort which was so cool! We snorkeled for 2 hours!! The best is right by the floating bungalows where they did massages. Speaking of massages....OMG! It was heaven!! Very affordable and different. When you lie face down, you look into a cut out in the floor, so you can view the water and fish swimming by. I loved it!! We did an island hopping tour and it was not an issue coming from this resort. When we got into Coron town and passed by all the hotels in that area, we were so glad and thankful we chose El Rio Y Mar. Coron Town is very dirty, dusty, full of young backpackers and the hotels look subpar. It's fine if you're on a budget. I get it, but us girls/mom/friends wanted to treat ourselves. That we did! One day we went on a guided hike to the top of a closeby mountain. The view was fantastic!! I highly recommend this resort and would definitely return.
Rating: 5
--------------------------------------------------------------------------------
MaricrisAndPiotr
Amazing staff
The best customer experience we ever had! the school of fishes within the resort are amazing, very quite, very clean and well maintained rooms and outdoor surroundings. Our island trip organized by them is one of the best experience we had in our Coron trip. 
Kudos to El Rio highly recommended
Rating: 5
--------------------------------------------------------------------------------

...and so on.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

抓取隐藏数据 [ window.__WEB_CONTEXT__= ] ...最好使用 Scrapy 的相关文章

随机推荐

  • 如何使用 PyQT5 连接和分离外部应用程序或对接外部应用程序?

    我正在使用 ROS 为多机器人系统开发 GUI 但我对界面中最不想做的事情感到困惑 在我的应用程序中嵌入 RVIZ GMAPPING 或其他屏幕 我已经在界面中放置了一个终端 但我无法解决如何向我的应用程序添加外部应用程序窗口的问题 我知道
  • SyntaxError:意外的令牌导入 TypeORM 实体

    因此 我正在使用 TypeORM 并且当我将 TypeScript 转换为 JavaScript 时遇到奇怪的错误 我收到以下错误 function exports require module filename dirname impor
  • WPF。如何将 InlineUIContainer 内容中的文本与 RichTextBox 中的外部文本对齐

    任务 使InlineUIContainer的文本内容与外部文本内联 InlineUIContainer 内容的标准行为是当底部边缘与外部文本内联时 可以使用 RenderTransform 移动 InlineUIContainer 的内容
  • Oracle(旧?)连接 - 用于转换的工具/脚本?

    我一直在移植 oracle selects 并且运行过很多查询 如下所示 SELECT e last name d department name FROM employees e departments d WHERE e departm
  • 调用 ToString("YYYY-mm-dd") 会导致日期格式错误

    我有一个构造函数 它需要一个DateTime object public Report DateTime date string start 0 string end 0 Logger Info Creating a new Report
  • 搜索30,000条SQL记录的方式

    我即将在我的网站上创建一个简单的搜索工具 用户将输入大约 2 4 个关键字 这些关键字将在我的 MS SQL 数据库表的两列中进行搜索 一列是 varchar 50 称为标题 一列是 varchar 2500 称为描述 任何时候都可能有大约
  • 如何使用 wxPython 检测窗口何时最小化?

    我正在编写一个小型 wxPython 实用程序 我想使用一些事件来检测用户何时最小化应用程序 窗口 我环顾四周 但没有找到像 wx EVT MINIMIZE 这样我可以绑定的事件 有人知道可以用来检测这一点的方法吗 添加一个处理程序wx E
  • 使用 ES6 导入 JSNLog 的正确语法是什么?

    我似乎不知道如何将 JSNLog 导入到我基于 ES6 babel 的 Aurelia 项目中 我试过了 import jsnlog JL is undefined import JL from jsnlog JL is import JL
  • 为什么 TensorFlow 尽管有多个核心却只能找到一个 CPU 设备?

    据我了解 TensorFlow 为每个核心创建一个设备 来源 https github com samjabrahams tensorflow white paper notes https github com samjabrahams
  • 确定未使用哪些 PHP 源文件

    我有一个大型网络应用程序 我认为有一堆不再使用的旧文件 是否有一个应用程序可以告诉我这些文件是什么 还有死码检测器 DCD http github com sebastianbergmann phpdcd 它会找到从未被调用的函数 这甚至可
  • 在表单调整大小时调整大量组件的性能问题

    我觉得到目前为止我的失败在于搜索词 因为这方面的信息必须非常普遍 基本上 我正在寻找在调整表单大小时对多个组件执行调整大小时的通用解决方案和最佳实践 我有一个表单 其组件基于TScrollBox ScrollBox 包含在运行时动态添加的行
  • 使用 JAXB 接口连接 EJB - XML

    我试图将 XML 模式添加到现有的 EJB 项目中 JAXB 用于将 XML 模式绑定到 Java 类 因为我们将在 EJB 处于会话状态时使用搜索引擎来爬取 DTO 我找不到任何将实体类文件映射到 XML 模式的直接方法 到目前为止 我们
  • 从受信任的应用程序访问 OS X 钥匙串项目

    我正在创建一个钥匙串 然后向其中添加一个带有预定义可信应用程序列表的项目 SecKeychainCreate keychainPath UTF8String UInt32 strlen keychainPass keychainPass F
  • 将字符串转换为 java.util.Date

    我有一个字符串作为 strikedate 2011 11 19T00 00 00 000 05 00 我需要将其放入 java util Date 中 谁能告诉我如何将此字符串转换为日期 当然 使用SimpleDateFormat http
  • 在 VBA 函数中访问各个数组元素

    VBA新手在这里 我正在尝试传递一个数组 它是静态的 但也请回答动态范围 到一个函数 然后将各个数组元素分配给唯一变量 并在自定义公式中使用这些变量 我只是浏览了一下并编写了代码 但不断收到 VALUE 错误 代码要点如下 Public F
  • iOS 8 中的自定义振动 - Swift

    我正在快速编写一个基于精灵套件的应用程序 需要使用振动进行简短的触觉反馈 所以首先我导入了 AudioToolbox 并使用了它 AudioServicesPlayAlertSound SystemSoundID kSystemSoundI
  • 映射两个矩阵的像素

    假设我有两个大小如下的矩阵 matrix 1 30090x2 matrix 2 170x177 这里假设数量rows n matrix 1代表数量pixels 你可以看到大小matrix 2等于像素数 我想做的是map中的像素matrix
  • Android随机活动不重复

    我正在开发一个问答游戏 我必须在回答问题时进行随机活动 以避免按相同顺序出现问题 我已经通过使用解决了这个问题switch 然而 问题是我可能会返回到我已经回答过的问题 所以我现在必须编写一些代码来避免玩家通过随机生成器转到之前的问题 到目
  • 如何修复多个样图中的颜色比例尺?

    我正在几个空气质量站之间进行 idw 插值 对于最终的可视化效果 我想将所有制作的图像折叠成 GIF 一切正常 唯一的问题是每个图像中值的比例会发生变化 并且比例会随着值 最小值 最大值 而变化 如何将颜色比例设置为固定值 这是一些示例数据
  • 抓取隐藏数据 [ window.__WEB_CONTEXT__= ] ...最好使用 Scrapy

    我正在爬到到网 我现在的问题是抓取给定酒店的 Hotelstars 不是平均用户评级 bubbles 而是酒店等级评级 稍后我将遇到隐藏在 阅读更多 后面的评论问题 https www tripadvisor com ph Hotel Re