【问题标题】:Python : extracting image source from HTML tag using Beautiful SoupPython:使用 Beautiful Soup 从 HTML 标签中提取图像源
【发布时间】:2018-08-05 03:45:02
【问题描述】:

我正在尝试单独打印图像 Src 标签值,我可以成功打印图像标签值,但无法获取 src 标签值。

import urllib3
import certifi
from urllib3 import PoolManager
from bs4 import BeautifulSoup

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
manager=PoolManager(num_pools=3,cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())

base_url="https://app.tipotapp.com/docs/quickstart/"
page=manager.request('GET',base_url)
soup = BeautifulSoup(page.data, 'html.parser')
idd='creating-an-application'

for sibling in soup.find(id=idd).next_siblings:
    if sibling.name is None :
       continue
    elif sibling.name != 'h2'  :
       print(sibling.getText())
       if sibling.img is not None:
          print(sibling.img)
          #print(sibling.select_one("img"))
       else:
          continue  
    else :   
        break

我现在得到的输出是,

打印: ....一些预期的字符串....然后是下面的输出

<img alt="Student Management System" 
src="https://app.tipotapp.com/docs/images/quickstart/image_004.png"/>

在那,我只想打印 src 值。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    要获取属性的值,请使用__getitem__(self, key) 方法。

    tag[key] 返回标签的 'key' 属性的值,如果不存在则抛出异常。

    只需将行 print(sibling.img) 替换为

    print(sibling.img['src'])
    

    输出:

    https://app.tipotapp.com/docs/images/quickstart/image_002.png
    https://app.tipotapp.com/docs/images/quickstart/image_002_1.png
    https://app.tipotapp.com/docs/images/quickstart/image_004.png
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 2021-12-04
      相关资源
      最近更新 更多