【问题标题】:Extract img inside description tag of xml file using Beautifulsoup使用 Beautifulsoup 在 xml 文件的描述标签中提取 img
【发布时间】:2013-10-30 06:38:49
【问题描述】:

我正在解析。我想在描述标签中获取图像。我正在使用 urllib 和 BeautifulSoup。我可以获取单独标签内的图像,但无法以编码格式获取描述标签内的图像。

Xml 代码

<item>
         <title>Kidnapped NDC member and political activist tells his story</title>
         <link>http://www.yementimes.com/en/1724/news/3065</link>
         <description>&lt;img src="http://www.yementimes.com/images/thumbnails/cms-thumb-000003081.jpg" border="0" align="left" hspace="5" /&gt;
‘I kept telling them that they would never break me and that the change we demanded in 2011 would come whether they wanted it or not’
&lt;br clear="all"&gt;</description>

views.py

for q in b.findAll('item'):
            d={}
            d['desc']=strip_tags(q.description.string).strip('&nbsp')
            if q.guid:
                d['link']=q.guid.string
            else:   
                d['link']=strip_tags(q.comments)
            d['title']=q.title.string
            for r in q.findAll('enclosure'):
                d['image']=r['url']
            arr.append(d)

谁能给我一个想法。
这就是我为解析单独标签内的图像所做的工作...... 我想知道它是否在描述中,但我不能。

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    您可以尝试从&lt;description&gt; 中提取所有内容,用它创建一个新的BeautifulSoup 对象并搜索第一个&lt;img&gt; 元素的src 属性:

    from bs4 import BeautifulSoup
    import sys 
    import html.parser
    
    h = html.parser.HTMLParser()
    
    soup = BeautifulSoup(open(sys.argv[1], 'r'), 'html')
    for i in soup.find_all('item'):
        d = BeautifulSoup(h.unescape(i.description.string))
        print(d.img['src'])
    

    像这样运行它:

    python3 script.py xmlfile
    

    产生:

    http://www.yementimes.com/images/thumbnails/cms-thumb-000003081.jpg
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 2019-05-11
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 2018-01-07
      相关资源
      最近更新 更多