【问题标题】:How to print the inner contents of a div with BeautifulSoup?如何使用 BeautifulSoup 打印 div 的内部内容?
【发布时间】:2018-06-24 13:46:42
【问题描述】:

网站的html如下:

<div class="breed-image">
    <img src = "link to image">
</div>

当我这样做时:

soup = BeautifulSoup(response.text, 'lxml')
for link in soup.find_all(class_='breed-image'):

    print(link)

它所做的只是打印出来:

<div class="breed-image">
</div>

我也试过 print(link.text)

所做的就是打印出来:

None

感谢任何形式的帮助,谢谢!

【问题讨论】:

    标签: python html python-3.x beautifulsoup


    【解决方案1】:

    看起来您最好使用此页面调用的 API 来获取其图像:

    In [13]: r = requests.get('https://dog.ceo/api/breeds/image/random')
    
    In [14]: r.json()
    Out[14]:
    {'message': 'https://dog.ceo/api/img/terrier-dandie/n02096437_1790.jpg',
     'status': 'success'}
    

    【讨论】:

      【解决方案2】:

      几个选项:

      >>> soup.img['src']
      'link to image'
      >>> for link in soup.find_all('img'):
      ...     print(link['src'])
      ...
      link to image
      

      【讨论】:

      • 对于第一个选项,它给了我错误TypeError: 'NoneType' object is not subscriptable,而对于第二个,它只是没有打印出任何东西
      • @Jonation McMurray 如果您想查看所有 html dog.ceo/dog-api/breeds-image-random.php,这里是链接
      • 看起来这个页面在 HTML 中没有 img,它是由一些嵌入式 Javascript 添加的 - 所以如果你正在下载这个页面,例如使用responses 模块,由于不执行JS,因此不会添加图像。这个问题可能会有所帮助:stackoverflow.com/questions/8049520/…
      • @MarkW 是的,那是在 JavaScript 执行之后 - JS 插入 img 标签,不执行 JS 源,没有 img 标签。如果您在浏览器中使用“查看源代码”而不是“检查”,则可以看到这一点
      猜你喜欢
      • 2021-10-29
      • 2018-11-08
      • 2016-02-17
      • 2020-03-24
      • 2015-09-28
      • 1970-01-01
      • 2011-01-16
      相关资源
      最近更新 更多