Python爬虫连载13-BeatuifulSoup四大对象、遍历文档对象、CSS选择器

1、BeautifulSoup四大对象node

1.Taggit

(1)对应的就是Html中的标签;github

(2)能够经过soup,tag_name正则表达式

(3)tag里面有两种重要的属性微信

name:用于打印标签的名字学习

attrs:用于打印属性(返回一个字典)大数据

contents:打印内容(返回一个列表)ui

 

from bs4 import BeautifulSoup

from urllib import request

​

url = "http://www.baidu.com"

rsp = request.urlopen(url)

content = rsp.read()

​

soup = BeautifulSoup(content)

#bs自动转码

content = soup.prettify()

print(content)

print("==" *12)

print(soup.head)

print("=="*12)

print(soup.link.name)

print("=="*12)

print(soup.link.attrs)

print(soup.link.attrs["type"])

print("=="*12)

print(soup.title)

print(soup.title.name)#打印标签

print(soup.title.attrs)

print(soup.title.contents)#打印内容,返回一个列表

2.NavigableStringurl

对应内容值spa

3.BeautileSoup

(1)表示的是一个文档的内容,大部分能够把它看成是tag对象

(2)通常能够使用soup来表示

4.Comment

(1)特殊类型的NavagableString对象

(2)对其输出,则内容不包括注释符号

2、遍历文档对象

1.contents:tag的子节点以列表的方式给出

2.children:子节点以迭代器的方式返回

3.decendants:全部的孙子节点

4.string

3、搜索文档对象

find_all(name,attrs,recursive,text,**kwargs)

​name:按照哪一个字符串搜索​,能够传入的内容:

(1)​字符串;(2)​正则表达式;(3)列表

kewwortd参数,能够用来表示属性

text:对应tag的文本值

 

from bs4 import BeautifulSoup

from urllib import request

import re

​

url = "http://www.baidu.com"

rsp = request.urlopen(url)

content = rsp.read()

​

soup = BeautifulSoup(content)

#bs自动转码

content = soup.prettify()

for node in soup.head.contents:

    if node.name == "meta":

        print(node)

print("=="*12)

​

tags = soup.find_all(name=re.compile("meta"))#能够使用正则,返回了一个列表,找的是含有meta属性的全部标签

print(tags)

print("=="*12)

4、CSS选择器

1.使用soup.select,返回一个列表

2.经过标签名称:soup.select("title")

3.​经过类名:soup.select(".content")

4.​经过id名:soup.select("#name_id")

5.组合​查找:soup.select("div #input_content")

6.属性​查找:soup.select("img[class="photo"])

7.​获取tag内容:tag.get_text

 

from bs4 import BeautifulSoup

from urllib import request

import re

​

url = "http://www.baidu.com"

rsp = request.urlopen(url)

content = rsp.read()

​

soup = BeautifulSoup(content)

​

print(soup.prettify())

print("=="*12)

titles = soup.select("title")

print(titles[0])

print("=="*12)

metas = soup.select("meta[content='always']")

print(metas)

5、源码

Reptile13_1_BeautifulSoupFourComponent.py

Reptile13_2_TraverseFileObject.py

Reptile13_3_CSSSelector.py

https://github.com/ruigege66/PythonReptile/blob/master/Reptile13_1_BeautifulSoupFourComponent.py

https://github.com/ruigege66/PythonReptile/blob/master/Reptile13_2_TraverseFileObject.py

https://github.com/ruigege66/PythonReptile/blob/master/Reptile13_3_CSSSelector.py

2.CSDN:https://blog.csdn.net/weixin_44630050

3.博客园:https://www.cnblogs.com/ruigege0000/

4.欢迎关注微信公众号:傅里叶变换,我的公众号,仅用于学习交流,后台回复”礼包“,获取大数据学习资料

 

相关文章
相关标签/搜索