zoukankan      html  css  js  c++  java
  • 读BeautifulSoup官方文档之html树的打印

    prettify()能返回一个格式良好的html的Unicode字符串 :

    markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
    soup = BeautifulSoup(markup)
    soup.prettify()
    # '<html>
     <head>
     </head>
     <body>
      <a href="http://example.com/">
    ...'
    
    print(soup.prettify())
    # <html>
    #  <head>
    #  </head>
    #  <body>
    #   <a href="http://example.com/">
    #    I linked to
    #    <i>
    #     example.com
    #    </i>
    #   </a>
    #  </body>
    # </html>

    但是你只是想要一个代表该html的字符串, 并不在乎它的格式, 你可以使用str()或者unicode()...这里str()返回的是格式为utf8的字符串, 你可以使用encode使它变为bytestring或者decode使它变成Unicode.

    str(soup)
    # '<html><head></head><body><a href="http://example.com/">I linked to <i>example.com</i></a></body></html>'
    
    unicode(soup.a)
    # u'<a href="http://example.com/">I linked to <i>example.com</i></a>'

    其他还有一些细节我不太像看下去了, 最后还有一个get_text()我在提下, 它能返回调用标签中所有的text部分...

    markup = '<a href="http://example.com/">
    I linked to <i>example.com</i>
    </a>'
    soup = BeautifulSoup(markup)
    
    soup.get_text()
    u'
    I linked to example.com
    '
    soup.i.get_text()
    u'example.com'

    你还可以为他传递一个字符串参数, 用这个参数来划分出每一部分的text.

    # soup.get_text("|")
    u'
    I linked to |example.com|
    '

    同时还可以设置strip参数来去掉每个部分(注意是每个部分而不是整体)前后的空白字符

    # soup.get_text("|", strip=True)
    u'I linked to|example.com'

    当然, 这种情况也可以使用我们之前提到的stripped_strings(), 不记得的可以看之前的文章...

    [text for text in soup.stripped_strings]
    # [u'I linked to', u'example.com']

    看到这里文档也看完了70%左右, 我感觉这些已经足够我目前的需求了, 所以就我不就继续往下看了...

  • 相关阅读:
    多线程,超时处理
    多线程,超时处理
    多线程,超时处理
    如何使用vue2搭建ElementUI框架
    pip 报错 ssl_.py:339: SNIMissingWarning: An HTTPS request has been made, but the SNI
    从单机到2000万QPS: 知乎Redis平台发展与演进之路
    OAuth2和JWT
    收集统计信息 不会更新DDL时间
    Python爬虫入门教程 8-100 蜂鸟网图片爬取之三
    Python爬虫入门教程 7-100 蜂鸟网图片爬取之二
  • 原文地址:https://www.cnblogs.com/nzhl/p/5593424.html
Copyright © 2011-2022 走看看