python BeautifulSoup对应关系

#!/usr/bin/python3
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup

#参考https://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#findAllNext%28name,%20attrs,%20text,%20limit,%20**kwargs%29%20and%20findNext%28name,%20attrs,%20text,%20**kwargs%29

def helloworld():
    print("hello world")
    pass

if __name__ == '__main__':

    xml = """<root>
        <book class="bookname" herf="http://www.baidu.com">helloPython</book>
        <book class="user">shz</book>
        <a herf="http://www.baidu.com"/>
        </root>"""
    bf= BeautifulSoup(xml,"lxml")
    print("==========================")
    tag = bf.find(class_ = "bookname") #类型是tag
    print("test: " + str(tag))  # <book class="bookname" herf="http://www.baidu.com">helloPython</book>
    print("name: " + tag.name)  # book
    print("text: " + tag.text)  # helloPython
    print("attrs: "  + str(tag.attrs))
    print("attr:herf: "  + str(tag["herf"]))
    print("attr:class: "  + str(tag["class"]))
    print("==========================")
    print("多个 返回list")
    print("==========================")
    tags= bf.findAll(name="book") #类型是tag
    print("test: " + str(tags))
    print("name: " + tags[1].name)
    print("==========================")
    print("多个 返回list")
    print("==========================")
    tags= bf.findAll(name="a") #类型是tag
    print("test: " + str(tags))
    print("name: " + tags[0].name)
    print("herf: " + tags[0]["herf"])
    pass
 

以上是测试代码

======================================================================

下面是输出结果

==========================
test: <book class="bookname" herf="http://www.baidu.com">helloPython</book>
name: book
text: helloPython
attrs: {'herf': 'http://www.baidu.com', 'class': ['bookname']}
attr:herf: http://www.baidu.com
attr:class: ['bookname']
==========================
多个 返回list
==========================
test: [<book class="bookname" herf="http://www.baidu.com">helloPython</book>, <book class="user">shz</book>]
name: book
==========================
多个 返回list
==========================
test: [<a herf="http://www.baidu.com"></a>]
name: a
herf: http://www.baidu.com
 

 

 

转载于:https://my.oschina.net/u/4000302/blog/2967385

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值