博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BeautifulSoup4的使用方法
阅读量:4618 次
发布时间:2019-06-09

本文共 2114 字,大约阅读时间需要 7 分钟。

BeautifulSoup是一个可以从HTML或XML文件中提取数据的Python库,它能实现文档的导航和查找,修改文档等操作

官方文档地址:""

几个常用提取信息工具的比较:

- 正则:很快,使用复杂,不用安装
- beautifulsoup:较慢,使用简单,安装简单
- lxml: 较快,使用简单,安装稍难

四大对象:

1.Tag

- 对应Html中的标签
- 可以通过soup.tag_name访问
- tag两个重要属性name和attrs

from urllib import requestfrom bs4 import BeautifulSoupurl = "http://www.baidu.com"rsp = request.urlopen(url)cnt = rsp.read()soup = BeautifulSoup(cnt, "lxml")cnt = soup.prettify()print(cnt)print("=="*10)print(soup.link)print(soup.link.name)print(soup.link.attrs)print(soup.link.attrs['type'])

2.NavigableString

- 对应内容值

3.BeautifulSoup

- 表示的是一个文档的内容,大部分可以把它当做tag对象
- 一般可以用soup来表示

4.Comment

- 特殊类型的NavagableString对象,对其输出,则内容不包括注释符号

遍历文档对象的方法:

- contents:返回tag子节点以列表的方式返回 
- children:返回tag子节点以迭代器形式返回
- descendants:返回所有子孙节点
- string:返回所有字符类型

from urllib import requestfrom bs4 import BeautifulSoupurl = "http://www.baidu.com"rsp = request.urlopen(url)cnt = rsp.read()soup = BeautifulSoup(cnt, "lxml")for node in soup.head.contents:    if node.name == 'meta':        print(node)    if node.name == 'title':        print(node.string)#
#
#
#
#百度一下,你就知道

搜索文档对象的方法:

使用find_all(name, attrs, recursive, text, ** kwargs)
- name:按照字符串搜索,可以传入的内容为字符串,正则表达式,列表
- kwargs参数,用来表示属性
- text:对应tag的文本值

from urllib import requestfrom bs4 import BeautifulSoupimport reurl = 'http://www.baidu.com'rsp = request.urlopen(url)content = rsp.read()soup = BeautifulSoup(content, 'lxml')tags = soup.find_all(re.compile('^me'), content="always")for tag in tags:    print(tag)#

CSS选择器的使用方法:

- 使用soup.select返回一个列表
- 通过标签名称: soup.select("title")
- 通过类名: soup.select(".content")
- id查找: soup.select("#name_id")
- 组合查找: soup.select("div #input_content")
- 属性查找: soup.select("img[class='photo'])
- 获取tag内容: tag.get_text

from urllib import requestfrom bs4 import BeautifulSoupurl = 'http://www.baidu.com'rsp = request.urlopen(url)content = rsp.read()soup = BeautifulSoup(content, 'lxml')titles = soup.select("title")print(titles[0])print("==" * 12)metas = soup.select("meta[content='always']")print(metas[0])#百度一下,你就知道#========================#

 

转载于:https://www.cnblogs.com/wjw2018/p/10615862.html

你可能感兴趣的文章
DynamicReports
查看>>
解决“System.Data.OracleClient需要Oracle客户端软件8.1.7或更高版本”
查看>>
什么是线程同步,什么是线程异步?同步的好处与弊端
查看>>
图片拉伸方法以及修改图片渲染模式以及如何把一个控制器包装成一个导航控制器...
查看>>
Oracle中的 UPDATE FROM 解决方法
查看>>
鼠标经过图像改变实现
查看>>
二分查找法
查看>>
Spring3升级到Spring4时, 运行时出现找不到MappingJacksonHttpMessageConverter的情况
查看>>
详解缓冲区溢出攻击以及防范方法
查看>>
分布式事务解决方案(一) 2阶段提交 & 3阶段提交 & TCC
查看>>
android之网格布局和线性布局实现注册页面
查看>>
BZOJ 1014: [JSOI2008]火星人prefix( splay + hash )
查看>>
js /jq 写 全选 反选 不选
查看>>
Denyhosts
查看>>
Regular Expression Matching leetcode
查看>>
关于循环中遍历的一些场景
查看>>
【转载】C/C++中的char,wchar,TCHAR
查看>>
SublimeText2 编辑器使用小结
查看>>
Debian 6 网络安装
查看>>
Python学习小记
查看>>