【问题标题】:href attribute for lxml.htmllxml.html 的 href 属性
【发布时间】:2015-02-05 08:22:10
【问题描述】:

据此answer

>>> from lxml.html import fromstring
>>> s = """<input type="hidden" name="question" value="1234">"""
>>> doc = fromstring(s)
>>> doc.value
'1234'
>>> doc.name
'question'

我试图从这段代码中获取链接和文本:

from lxml.html import fromstring
s = '<a href="http://a.com" rel="bookmark">bla bla bla</a>'
doc = fromstring(s)
print (doc.href)
print (doc.text_content())

它给出了AttributeError:'HtmlElement' object has no attribute 'href'

我是 lxml 的新手。其实问题出在哪里?

如何将链接 (a.com) 和文本 (bla bla bla) 作为此代码中的字符串?

【问题讨论】:

    标签: python-3.4 lxml.html


    【解决方案1】:

    此代码适用于我

    from lxml.html import document_fromstring
    doc = document_fromstring('<a href="http://a.com" rel="bookmark">bla bla bla</a>')
    print (doc.xpath("//a")[0].get("href"))
    print (doc.text_content())
    

    输出:

    http://a.com
    bla bla bla
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 2012-10-13
    • 2012-02-05
    • 2016-06-07
    • 2013-06-27
    • 2014-10-21
    • 2014-07-21
    相关资源
    最近更新 更多