当前位置: 首页>>代码示例>>Python>>正文


Python DOM.get_elements_by_tagname方法代码示例

本文整理汇总了Python中pattern.web.DOM.get_elements_by_tagname方法的典型用法代码示例。如果您正苦于以下问题:Python DOM.get_elements_by_tagname方法的具体用法?Python DOM.get_elements_by_tagname怎么用?Python DOM.get_elements_by_tagname使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pattern.web.DOM的用法示例。


在下文中一共展示了DOM.get_elements_by_tagname方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: DOM

# 需要导入模块: from pattern.web import DOM [as 别名]
# 或者: from pattern.web.DOM import get_elements_by_tagname [as 别名]
# The DOM (Document Object Model) parses a string of HTML
# and returns a tree of nested Element objects.
# The DOM elements can then be searched by tag name, CSS id, CSS class, ...

# For example, top news entries on Reddit are coded as:
# <div class="entry">
#     <p class="title">
#         <a class="title " href="http://i.imgur.com/yDyPu8P.jpg">Bagel the bengal, destroyer of boxes</a>
#     ...
# </div>
#
# ... which - naturally - is a picture of a cat.
url = URL("http://www.reddit.com/top/")
dom = DOM(url.download(cached=True))
# print dom.body.content
for e in dom.get_elements_by_tagname("div.entry")[:5]:  # Top 5 reddit entries.
    for a in e.get_elements_by_tagname("a.title")[:1]:  # First <a class="title"> in entry.
        print plaintext(a.content)
        print a.attributes["href"]
        print

# The links in the HTML source code may be relative,
# e.g., "../img.jpg" instead of "www.domain.com/img.jpg".
# We can get the absolute URL by prepending the base URL.
# However, this can get messy with anchors, trailing slashes and redirected URL's.
# A good way to get absolute URL's is to use the module's abs() function:
from pattern.web import abs

url = URL("http://nodebox.net")
for link in DOM(url.download()).by_tag("a"):
    link = link.attributes.get("href", "")
开发者ID:sarawutc,项目名称:pattern,代码行数:33,代码来源:12-dom.py


注:本文中的pattern.web.DOM.get_elements_by_tagname方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。