【问题标题】:BeautifulSoup wait for JavaScript/Angular contentBeautifulSoup 等待 JavaScript/Angular 内容
【发布时间】:2017-01-13 19:50:35
【问题描述】:

我正在尝试使用 python 从某个 url 获取所有图像。

所以美丽汤的用法是海峡前进,但我面临的问题是,并非所有的 img 标签都打印在控制台中。仔细查看所需的 HTML 文件会发现丢失的图像来自 Angular,因为它们有一个 data-ng-src 标记。

有什么方法可以让soup 等到所有脚本都完成了吗?或者有没有其他方法可以检测所有的img标签?

到目前为止我的代码:

import urllib2
from BeautifulSoup import BeautifulSoup

page = BeautifulSoup(urllib2.urlopen(url))
allImgs = imgs = page.findAll('img')
print allImgs

【问题讨论】:

标签: javascript python html angularjs beautifulsoup


【解决方案1】:

图像不会插入到它们链接到的 HTML 页面中。 对于需要一些等待/暂停时间的事情,我宁愿 使用 Selenium Web 驱动程序。我认为 Beautiful Soup 正在阅读页面 一次全部。我认为它是令人生畏的包装 解析文件的琐事,但不能作为与页面交互的工具。

【讨论】:

    【解决方案2】:

    您可以尝试使用硒。虽然这个库是用来做自动化测试的,但是功能比BeautifulSoup丰富很多

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    
    url ='http://example.com/'
    driver = webdriver.Firefox()
    driver.get(url)
    
    delay = 5 # seconds
    
    try:
        WebDriverWait(driver, delay).until(EC.presence_of_element_located(driver.find_elements_by_xpath('..//elementid')))
        print "Page is ready!"
        for image in driver.find_elements_by_xpath('..//img[@src]'):
            print image.get_attribute('src')
    except TimeoutException:
        print "Couldn't load page"
    

    还请阅读以下帖子;谈使用JS动态加载页面
    https://stackoverflow.com/a/11460633/6626530

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-15
      • 2011-04-17
      • 2019-01-22
      • 1970-01-01
      • 2019-05-24
      • 2021-09-15
      • 1970-01-01
      相关资源
      最近更新 更多