爬虫学习3——BeautifulSoup

没啥废话,直接开始吧,新建一个Python文件,对着练习就行了。
可以添加print查看程序执行情况。

from bs4 import BeautifulSoup
#测试的网页源码
html_doc = """    
<html>
        <head>
                <title>The Dormouse's story</title>
        </head>
        <body>
    <p class="story">Once upon a time there were many children and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
    <a href="http://example.com/Bob" class="sister" id="link4">Bob</a>;
    <a href="http://example.com/King" class="brother" id="link5">King</a>;
    <a href="http://example.com/Mary" class="sister" id="link6">Mary</a>;
    <a href="http://example.com/Target" class="sister" id="link7">Target said:“I am very strong”</a>;
    <a href="http://example.com/Jack" class="brother" id="link8">Jack</a>;
    and they lived at the bottom of a well.
    </p>

                <p class="story">...</p>
"""

bs = BeautifulSoup(html,'lxml')   #使用lmxl进行解析html

doc = bs.prettify    #把代码格式化输出

doc = bs.title.string   #获取title标签的内容
doc = bs.title.text    #同样是获取title标签的内容
doc = bs.a.text    #获取a标签的内容
doc = bs.a.string  #获取a标签的内容

doc = bs.title   #获取title标签

doc = bs.head   #获取出head标签

doc = bs.body.a  #获取body下的a标签,但是只是打印第一个,镶嵌选择

doc = bs.p['class']   #获取p标签的属性class属性

doc = bs.find_all('a')   #获取所有的a标签

doc = bs.find('a')   #查找a标签,只是返回查找的第一个

doc = bs.a.parent   #获取a标签的父标签

doc = bs.a.parents   #获取a标签的祖先标签
#print(type(doc))   #祖先标签是generator类型,通过for循环打印
#for item in doc:
#    print(item)

doc = bs.a.next_sibling  #获取a标签的下一个兄弟节点
#print(doc)
#for item in doc:   获取所有兄弟节点靠for循环输出
#    print(item)

#find_next_silbings()  返回后面的所有兄弟标签
#find_previous_sibilings()  返回前面的所有兄弟标签
#find_next_silbing()  返回后面的第一个兄弟标签
#find_previous_sibiling()  返回前面的第一个兄弟标签

doc = bs.find_all('a')  #查找所有的a标签

doc = bs.find_all(attrs={'id':'link1'})   #通过属性查找所有的标签
doc = bs.find_all(attrs={'id':'link3'})   #通过属性查找所有的标签

doc = bs.find_all(id='link3')   #通过id直接查找,而不是通过字典查找
doc = bs.find_all(class_='brother')   #class后面有个 _

doc = bs.find_all(text='Target') #根据文本内容查找,文本内容必须要完全匹配才能查找上,这个就找不到
doc = bs.find_all(text='Bob')  #这个能查找上

#find_all_next()  返回节点后所有符合条件的节点
#find_next()   返回节点后第一个符合条件的节点

doc = bs.select('#link3')  #这里的select是bs中内置的css选择器,可以直接通过css选择
doc = bs.select('.brother')  #通过id进行查找
doc = bs.select('p a')  #获取p标签下的所有a标签

doc = bs.select('a')   #获取所有的a标签,并输出每个的href的属性内容,需要通过for循环输出
#for item in doc:
#    print(item['href'])

doc = bs.select('a')   #获取所有的a标签,并输出每个标签的内容,需要通过for循环输出
#for item in doc:
#    print(item.text)

猜你喜欢

转载自blog.51cto.com/13155409/2124420
今日推荐