【发布时间】:2017-12-22 04:50:32
【问题描述】:
我正在尝试在Shopee 上抓取网站列表。一些示例包括dudesgadget 和2ubest。这些 Shopee 商店中的每一个都有不同的设计和构建 Web 元素的方式以及不同的域。它们看起来像独立的网站,但实际上并非如此。
所以这里的主要问题是我试图抓取产品详细信息。我将总结一些不同的结构:
2最佳
<html>
<body>
<div id="shopify-section-announcement-bar" id="shopify-section-announcement-bar">
<main class="wrapper main-content" role="main">
<div class="grid">
<div class="grid__item">
<div id="shopify-section-product-template" class="shopify-section">
<script id="ProductJson-product-template" type="application/json">
//Things I am looking for
</script>
</div>
</div>
</div>
</main>
</div>
</body>
</html>
<html>
<body id="adjustable-ergonomic-laptop-stand" class="template-product">
<script>
//Things I am looking for
</script>
</body>
</html>
还有一些其他的,我发现了它们之间的一种模式。
- 我正在寻找的东西肯定会在
<body> - 我正在寻找的东西在
<script>内 - 我唯一不确定的是
<body>到<script>的距离
我的解决办法是:
def parse(self, response):
body = response.xpath("//body")
for script in body.xpath("//script/text()").extract():
#Manipulate the script with js2xml here
我能够提取littleplayland、dailysteals 和许多其他从<body> 到<script> 的距离非常短的,但不适用于有很多其他html 的2ubest我正在寻找的东西之间的元素。我可以知道是否有解决方案可以忽略其间的所有 html 元素而只查找 <script> 标记?
我需要一个通用的单一解决方案,如果可能的话,可以在所有Shopee 网站上工作,因为它们都具有我上面提到的特征。
这意味着该解决方案不应使用 <div> 进行过滤,因为每个不同的网站都有不同数量的 <div>
【问题讨论】:
-
body.xpath("//script/text()")应该在 HTML 中为您提供所有<script>- 如果它不是由 JavaScript 添加的话。 -
问题是当它之间有太多
<div>时,它什么也没给我。只有当<div>的深度很少时,它才会给我一些回报。深度限制默认为0,不是限制,但不知道为什么会停在xhtml标签深度数 -
如果你意识到,
for loop中的script已经是来自<script>的text()(如果有的话),但是当 html 标记深度太高时它没有返回任何问题 -
它不应该有任何深度的问题。我在其他工具中看到的唯一问题是它在
<iframe>标签内,因为<iframe>内的代码是分开的页面/文件。 -
也许你应该准确地知道这个
<script>里面的内容,这样我们就可以在HTML中检查它了。
标签: python xpath web-scraping scrapy