网页抓取:根据结果展开/收缩边界框

2024-09-28 15:12:28 发布

您现在位置:Python中文网/ 问答频道 /正文

一个客户想知道他们竞争对手的商店的位置,所以我是在“准邪恶”和“刮”竞争对手的网站。在

服务器接受边界框(即,左下角和右上角坐标)作为参数,并返回在边界框内找到的位置。这个部分工作得很好,我可以成功地检索到给定边界框的商店位置。在

问题是只返回边界框中的前10个位置,因此在人口稠密的区域,10度边界框将返回太多位置:

enter image description here

我可以一直使用一个较小的边界框,但我在确保返回所有存储的同时,尽量避免对服务器的不必要的访问。在

因此,我需要一种方法,当找到10个存储时,减小搜索矩形的大小(因为可能存在10个以上的存储),然后递归地使用较小的搜索矩形大小进行搜索,然后为下一个网格单元还原为更大的矩形。在

我编写了一个函数,该函数通过给定的边界框从服务器检索存储:

stores = checkForStores(<bounding box>)
if len(stores) >= 10:
  # There are too many stores. Search again with a smaller bounding box
else:
  # Everything is good - process these stores

但是我正在为如何为checkForStores函数设置适当的边界框而苦苦挣扎。在

我尝试过在经纬度上使用for循环来设置主网格单元:

^{pr2}$

。。。但我不知道如果找到10家商店,如何用一个较小的边界框继续搜索。我也尝试过使用while循环,但是我不能让它们中的任何一个起作用。在

谢谢你的建议和建议。在


Tags: 函数服务器box网格客户网站建议stores
1条回答
网友
1楼 · 发布于 2024-09-28 15:12:28

下面是如何使用递归实现它。代码应该是不言自明的,但它的工作原理如下: 给定一个边界框,它检查其中存储的数量,如果超过或等于10个,则将这个框分成更小的,并用每个新的边界框调用自己。直到找到不到10家店为止。在这种情况下,找到的商店只是保存在列表中。在

注意:由于使用递归,所以可能会出现超出最大递归深度的情况。这是理论上的。在您的例子中,即使您通过4000x4000km边界框,也只需15步就可以到达粗略的1x1km边界框cell_axis_reduction_factor=2

In [1]: import math

In [2]: math.log(40000, 2)
Out[2]: 15.287712379549449

无论如何,在这种情况下,您可以尝试增加cell_axis_reduction_factor个数。在

还要注意:在Python中,根据PEP 8,函数应该是小写的,带有下划线,所以我将checkForStores函数重命名为check_for_stores。在

^{pr2}$

下面是一个输出示例:

Checking for stores...
Found 10 stores for bounding box ((0, 1), (30, 20)).
Stores number is more than or equal 10. Splitting bounding box...
Checking for stores...
Found 4 stores for bounding box ((0.0, 1.0), (15.0, 10.5)).
Stores number is less than 10. Saving results.
Checking for stores...
Found 4 stores for bounding box ((0.0, 10.5), (15.0, 20.0)).
Stores number is less than 10. Saving results.
Checking for stores...
Found 10 stores for bounding box ((15.0, 1.0), (30.0, 10.5)).
Stores number is more than or equal 10. Splitting bounding box...
Checking for stores...
Found 1 stores for bounding box ((15.0, 1.0), (22.5, 5.75)).
Stores number is less than 10. Saving results.
Checking for stores...
Found 9 stores for bounding box ((15.0, 5.75), (22.5, 10.5)).
Stores number is less than 10. Saving results.
Checking for stores...
Found 4 stores for bounding box ((22.5, 1.0), (30.0, 5.75)).
Stores number is less than 10. Saving results.
Checking for stores...
Found 1 stores for bounding box ((22.5, 5.75), (30.0, 10.5)).
Stores number is less than 10. Saving results.
Checking for stores...
Found 6 stores for bounding box ((15.0, 10.5), (30.0, 20.0)).
Stores number is less than 10. Saving results.
Found 29 stores in total
Visited boxes: 
[
((0, 1), (30, 20)), 
((0.0, 1.0), (15.0, 10.5)), 
((0.0, 10.5), (15.0, 20.0)), 
((15.0, 1.0), (30.0, 10.5)), 
((15.0, 1.0), (22.5, 5.75)), 
((15.0, 5.75), (22.5, 10.5)), 
((22.5, 1.0), (30.0, 5.75)), 
((22.5, 5.75), (30.0, 10.5)), 
((15.0, 10.5), (30.0, 20.0))
]

相关问题 更多 >