页面源代码未显示selenium/Python的广告

2024-06-17 13:02:21 发布

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

这应该是一个非常直接的元素查找,只是没有发生,我添加了一个非常长的隐式等待,以允许页面完全加载

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.get("https://www.smh.com.au")
driver.find_elements_by_class_name("img_ad")

以及基于元素位置的等待负载

timeout = 10    
try:
    element_present = EC.presence_of_element_located((By.CLASS_NAME, '"img_ad'))
    WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
    print("Timed out waiting for page to load")

然而,尽管我在firefox的inspect模式下看得很清楚,但这个元素并没有出现

<img src="https://tpc.googlesyndication.com/simgad/9181016285467049325" alt="" class="img_ad" width="970" height="250" border="0">

这是网页上的一则广告,所以我认为上面可能有一些不在驱动程序中显示的时髦代码,关于如何收集这些代码有什么建议吗


Tags: 代码fromhttpscom元素imgdriverselenium
1条回答
网友
1楼 · 发布于 2024-06-17 13:02:21

广告位于iFrame中,因此您需要先切换此帧

但我发现,在几次页面加载之后,广告就不再出现在网页上了。我确实发现,几乎每次使用driver = webdriver.Opera()都会加载广告,但不是在Firefox的Chrome浏览器中加载,甚至使用私人浏览和清除所有浏览数据

如果它们出现了,那么这个代码就起作用了

要通过部分类名查找元素,我首先使用find_element_by_css_selector("amp-img[class^='img_ad']")。有时带有img_ad类的元素不存在,因此可以使用driver.find_element_by_id("aw0")更频繁地查找数据。有时网页HTML甚至没有这个id,所以我的代码打印HTML

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException


driver = webdriver.Firefox()
driver.get("https://www.smh.com.au")
driver.implicitly_wait(10)

iFrame = driver.find_elements_by_tag_name("iframe")[1]
driver.switch_to.frame(iFrame)

try:
    # element = driver.find_element_by_css_selector("amp-img[class^='img_ad']")
    # print(element.get_attribute('outerHTML'))
    element = driver.find_element_by_id("aw0")
    print(element.get_attribute('innerHTML'))
except NoSuchElementException:
    print("Advert not found")
    print(driver.page_source)

driver.quit()

产出:

<amp-img alt="" class="img_ad i-amphtml-layout-fixed i-amphtml-layout-size-defined i-amphtml-element i-amphtml-layout" height="250" i-amphtml-layout="fixed" i-amphtml-ssr="" src="https://tpc.googlesyndication.com/simgad/16664324514375864185" style="width:970px;height:250px;" width="970"><img alt="" class="i-amphtml-fill-content i-amphtml-replaced-content" decoding="async" src="https://tpc.googlesyndication.com/simgad/16664324514375864185"></amp-img>

或:

<img src="https://tpc.googlesyndication.com/simgad/10498242030813793376" border="0" width="970" height="250" alt="" class="img_ad">

或:

<html><head></head><body></body></html>

相关问题 更多 >