【问题标题】:Python - Can't access some tags using LXML.HTMLPython - 无法使用 LXML.HTML 访问某些标签
【发布时间】:2013-03-07 09:04:58
【问题描述】:

又是一个问题,抱歉所有帖子。昨天用户“J.F. Sebastian”给了我一个很好的提示,让我使用 LXML.HTML 而不是只使用 LXML。

我今天将它用于另一个提要http://feeds.bbc.co.uk/iplayer/search/tv/?q=news,但我无法访问内容元素中的几个标签。

以下是 Feed 数据示例:

  <entry>
    <title type="text">BBC News at Six: 06/03/2013</title>
    <id>tag:feeds.bbc.co.uk,2008:PIPS:b01r27mt</id>
    <updated>2013-03-07T00:20:38Z</updated>
    <content type="html">
      &lt;p&gt;
    &lt;a href=&quot;http://www.bbc.co.uk/iplayer/episode/b01r27mt/BBC_News_at_Six_06_03_2013/&quot;&gt;
      &lt;img src=&quot;http://ichef.bbci.co.uk/programmeimages/episode/b01r27mt_150_84.jpg&quot; alt=&quot;BBC News at Six: 06/03/2013&quot; /&gt;
    &lt;/a&gt;
      &lt;/p&gt;
      &lt;p&gt;
    National and international news stories from the BBC News team, followed by weather.
      &lt;/p&gt;
    </content>
    <category term="News" />
    <category term="TV" />
    <link rel="alternate" href="http://www.bbc.co.uk/iplayer/episode/b01r27mt/BBC_News_at_Six_06_03_2013/" type="text/html" title="BBC News at Six: 06/03/2013">
      <media:content>
    <media:thumbnail url="http://ichef.bbci.co.uk/programmeimages/episode/b01r27mt_150_84.jpg" width="150" height="84" />
      </media:content>
    </link>
    <link rel="self" href="http://feeds.bbc.co.uk/iplayer/episode/b01r27mt" type="application/atom+xml" title="06/03/2013" />
    <link rel="related" href="http://www.bbc.co.uk/programmes/b007mpkn/microsite" type="text/html" title="BBC News at Six" />
  </entry>

内容标签中的标签似乎是文本,无法正确解析。这是我的代码:

tree = html.parse("http://feeds.bbc.co.uk/iplayer/search/tv/?q=news")
for show in tree.xpath('//entry'):
    select = lambda expr: show.cssselect(expr)[0]
    icon_url=select("thumbnail").get('url')
    print "icon_url: ", icon_url
    name=select('title').text_content()
    print "name: ", name
    stream=select('id').text_content()
    print "stream: ", stream
    date=select('updated').text_content()
    print "date: ", date
    content=select('content').text_content()
    print "content: ", content
    #links = (re.compile ('\n      &lt;p&gt;\n        &lt;a href=&quot;.+?&quot;&gt;\n          &lt;img src=&quot;(.+?)&quot; alt=&quot;.+?&quot; /&gt;\n        &lt;/a&gt;\n      &lt;/p&gt;\n      &lt;p&gt;\n     ').findall(content))
    #print "links: ", links
    #short=links
    #print "short: ", short

我想将带有程序描述的第二个 p 标签放入上面的短变量中,但我似乎无法使用 lxml 选择此标签,并且我无法让正则表达式在选择我想要的行时起作用..

有什么想法吗?

【问题讨论】:

    标签: python regex parsing lxml


    【解决方案1】:

    您需要取消引用该文本以获取 html,然后再次对其进行解析。

    来自here

    from xml.sax import saxutils as su
    
    unqoutedHtml = su.unescape(content)
    newElement = html.document_fromstring(unqoutedHtml)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-18
      • 2022-12-21
      • 2016-01-17
      • 1970-01-01
      • 2011-10-25
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多