【问题标题】:Python-Selenium : Not able to scrape image from html/javascript stringPython-Selenium:无法从 html/javascript 字符串中抓取图像
【发布时间】:2019-05-21 13:03:55
【问题描述】:

我有一个 HTML 字符串,我从 PhanthomJs 在浏览器中打开它并尝试保存结果 URL。

我的代码如下所示。

driver.get("data:text/html;charset=utf-8,{html_content}".format(html_content=html_content))
element = driver.find_element_by_tag_name('body')
elem =  element.find_element_by_tag_name('noscript')
print elem.find_element_by_tag_name('img')

html_content 如下所示。

<script language="javascript" src="https://somejs"></script>
<noscript>
<a href="https://track.adform.net/C/?bn=15864640;C=0" target="_blank">
<img src="https://actualimage.net/verbserve/?bn=155679864640;srctype=4;ord=[timestamp]" border="0" width="728" height="90" alt=""/>
</a>
</noscript>

当我将图像作为 html 文件在本地运行时,html 会渲染图像。

我想用上面提到的代码保存该图像。但不幸的是,我无法使用 find_element_by_tag_name 找到 img

我遇到了错误。

selenium.common.exceptions.NoSuchElementException: Message: {"errorMessage":"Unable to find element with tag name 'img'","request"

请让我知道我在这里做错了什么。

【问题讨论】:

    标签: python selenium beautifulsoup


    【解决方案1】:

    试试这个,如果简单的 HTML 内容不是网页内容

    from bs4 import BeautifulSoup
    
    html_content = """ <script language="javascript" src="https://somejs"></script>
    <noscript>
    <a href="https://track.adform.net/C/?bn=15864640;C=0" target="_blank">
    <img src="https://actualimage.net/verbserve/?bn=155679864640;srctype=4;ord=[timestamp]" border="0" width="728" height="90" alt=""/>
    </a>
    </noscript>""" 
    
    
    sp = BeautifulSoup(html_content,'html.parser')
    
    elem =  sp.find('noscript')
    
    img = elem.find('img') 
    print(img['src'])
    

    O/P:

    https://actualimage.net/verbserve/?bn=155679864640;srctype=4;ord=[timestamp]

    按网址抓取网页内容:

    driver = webdriver.Chrome("/usr/bin/chromedriver")
    driver.get('http://www.test.com')
    
    sp = BeautifulSoup(driver.page_source,'html.parser')
    
    elem =  sp.find('noscript')
    
    img = elem.find('img') 
    print(img['src'])
    

    "/usr/bin/chromedriver"chrome 驱动路径在哪里

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 2017-12-09
      • 2019-08-06
      • 2021-05-26
      • 1970-01-01
      相关资源
      最近更新 更多