有没有一种(简单的)方法可以使用Python计算广告在网页中所占的百分比(物理)空间?

2024-10-03 02:40:28 发布

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

问题陈述是这样的:找到网页上广告的实际占有率%

比如说,我有一个URL,打开时有它的内容和3个广告——一个是图像广告,另外2个是“图像和文本”广告(我收到了很多这样的URL,但广告数量不详)。我根据bin类中包含“广告”或“赞助”的广告数量进行统计,因此我知道其页面上有3个广告。现在,我需要找出这些广告占整个网页的百分比,也就是说,三个广告加起来占整个网页的20%。我该怎么做

我知道元素在不同的浏览器中呈现不一样,实际上我并不关心这一点。我只需要一个基于Chrome(或Firefox-任何东西都可以)的粗略百分比

2013年提出的一个类似问题How to programmatically measure the elements' sizes in HTML source code using python?只有两个解决方案,信息不多。我发现所建议的包Ghost的API(询问者认为有用的那个)很难理解

我被要求使用无头浏览器“呈现一个网站”,首先是没有广告的,然后是有广告的,并找到不同之处。问题是,我不知道怎么做。我也只是希望在过去的8年里,有人能想出一个更简单的方法来解决这个问题

由于我不熟悉用Python以这种方式进行“刮取”——如果可以称之为“刮取”——我可以使用您可能知道的任何资源/想法/文档


Tags: 图像文本url元素网页内容数量bin
1条回答
网友
1楼 · 发布于 2024-10-03 02:40:28

我们可以使用.size方法计算所有元素的高度和宽度

xpath查找所有元素:

//*

然后我们可以计算广告、高度和宽度,因为它们是web元素,所以我们可以使用相同的.size方法

演示如下:

driver.maximize_window()
driver.implicitly_wait(30)
driver.get("https://stackoverflow.com/questions/68453828/is-there-a-simple-way-to-calculate-the-percentage-physical-space-occupied-by?noredirect=1#comment120979267_68453828")
wait = WebDriverWait(driver, 10)
width = []
height = []
for element in driver.find_elements(By.XPATH, "//*"):
    size = element.size
    w, h = size['width'], size['height']
    width.append(w)
    height.append(h)

total_width = sum(width)
total_height = sum(height)

print(total_width, total_height)

# Now calculate the width and heights of ads,

first_ad = wait.until(EC.visibility_of_element_located((By.XPATH, "//img")))
first_ad_size = first_ad.size
first_ad_w, first_ad_h = first_ad_size['width'], first_ad_size['height']

print(first_ad_w, first_ad_h)

total_page_area = total_width * total_height
print(total_page_area)

image_area = first_ad_w * first_ad_h
print(image_area)

percentage = (image_area * 100 )/total_page_area
print(percentage)

导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

PS:我采用了first image as an ad(我知道这并不理想,只是为了给OP提供一种实现此功能的方法)

如果你能用一个通用的定位器(xpath,css)定位所有的广告,那就更容易了

相关问题 更多 >