Python3.x的BeautifulSoup解析html常用函数
Python3.x的BeautifulSoup解析html常用函数
1,初始化:
soup = BeautifulSoup(html) # html为html源代码字符串,type(html) == str
2,用tag获取相应代码块的剖析树:
#当用tag作为搜索条件时,我们获取的包含这个tag块的剖析树:
#<tag><xxx>ooo</xxx></tag>
#这里获取head这个块
head = soup.find('head')
# or
# head = soup.head
# or
# head = soup.contents[0].contents[0]
contents属性是一个列表,里面保存了该剖析树的直接儿子,如:
html = soup.contents[0] # <html> ... </html>
head = html.contents[0] # <head> ... </head>
body = html.contents[1] # <body> ... </body>
3,用contents[], parent, nextSibling, previousSibling寻找父子兄弟tag:
beautifulSoup提供了几个简单的方法直接获取当前tag块的父子兄弟。
假设我们已经获得了body这个tag块,我们想要寻找<html>, <head>, 第一个<p>, 第二个<p>这四个tag块:
# body = soup.bodyhtml = body.parent # html是body的父亲
head = body.previousSibling # head和body在同一层,是body的前一个兄弟
p1 = body.contents[0] # p1, p2都是body的儿子,我们用contents[0]取得p1
p2 = p1.nextSibling # p2与p1在同一层,是p1的后一个兄弟, 当然body.content[1]也可得到 print(p1.text)
# u'This is paragraphone.'
print(p2.text)
# u'This is paragraphtwo.'
# 注意:1,每个tag的text包括了它以及它子孙的text。2,所有text已经被自动转
#为unicode,如果需要,可以自行转码encode(xxx)
4,用find, findParent, findNextSibling, findPreviousSibling寻找祖先或者子孙 tag:
find方法(我理解和findChild是一样的),就是以当前节点为起始,遍历整个子树,找到后返回。
而这些方法的复数形式,会找到所有符合要求的tag,以list的方式放回。他们的对应关系是:find->findall, findParent->findParents, findNextSibling->findNextSiblings...,如:
print soup.findAll('p')
# [<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>, <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>]
5,find的几种用法,其他的类比: find(name=None, attrs={}, recursive=True, text=None, **kwargs),文档参考: https://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#The%20basic%20find%20method:%20findAll%28name,%20attrs,%20recursive,%20text,%20limit,%20**kwargs%29)
(1).搜索tag:
find(tagname) # 直接搜索名为tagname的tag 如:find('head')
find(list) # 搜索在list中的tag,如: find(['head', 'body'])
find(dict) # 搜索在dict中的tag,如:find({'head':True, 'body':True})
find(re.compile('')) # 搜索符合正则的tag, 如:find(re.compile('^p')) 搜索以p开头的tag
find(lambda) # 搜索函数返回结果为true的tag, 如:find(lambda name: if len(name) == 1) 搜索长度为1的tag
find(True) # 搜索所有tag
(2),搜索属性(attrs):
find(id='xxx') # 寻找id属性为xxx的
find(attrs={id=re.compile('xxx'), algin='xxx'}) # 寻找id属性符合正则且algin属性为xxx的
find(attrs={id=True, algin=None}) # 寻找有id属性但是没有algin属性的
(3),搜索文字(text):
注意:文字的搜索会导致其他搜索给的值如:tag, attrs都失效。
方法与搜索tag一致;
(4),recursive, limit:
recursive=False表示只搜索直接儿子,否则搜索整个子树,默认为True。
当使用findAll或者类似返回list的方法时,limit属性用于限制返回的数量,如findAll('p', limit=2): 返回首先找到的两个tag
Python3.x的BeautifulSoup解析html常用函数的更多相关文章
- Python3.x:BeautifulSoup()解析网页内容出现乱码
Python3.x:BeautifulSoup()解析网页内容出现乱码 问题: start_html = requests.get(all_url, headers=Hostreferer) Beau ...
- python3 内置常用函数系列一
python3 内置了一系列的常用函数, python英文官方文档详细说明:点击查看, 为了方便查看,将内置常用的函数的记录一下来. Python3版本所有的内置函数: 1.abs() print(a ...
- Python3 urllib.parse 常用函数示例
Python3 urllib.parse 常用函数示例 http://blog.51cto.com/walkerqt/1766670 1.获取url参数. >>> from url ...
- numpy.random模块常用函数解析
numpy.random模块中常用函数解析 numpy.random模块官方文档 1. numpy.random.rand(d0, d1, ..., dn)Create an array of the ...
- python重要的第三方库pandas模块常用函数解析之DataFrame
pandas模块常用函数解析之DataFrame 关注公众号"轻松学编程"了解更多. 以下命令都是在浏览器中输入. cmd命令窗口输入:jupyter notebook 打开浏览器 ...
- pandas模块常用函数解析之Series(详解)
pandas模块常用函数解析之Series 关注公众号"轻松学编程"了解更多. 以下命令都是在浏览器中输入. cmd命令窗口输入:jupyter notebook 打开浏览器输入网 ...
- python3+beautifulSoup4.6抓取某网站小说(三)网页分析,BeautifulSoup解析
本章学习内容:将网站上的小说都爬下来,存储到本地. 目标网站:www.cuiweijuxs.com 分析页面,发现一共4步:从主页进入分版打开分页列表.打开分页下所有链接.打开作品页面.打开单章内容. ...
- Python3.x:bs4解析html基础用法
Python3.x:bs4解析html基础用法 代码: import urllib.request from bs4 import BeautifulSoup import re url = r'ht ...
- 第14.11节 Python中使用BeautifulSoup解析http报文:使用查找方法快速定位内容
一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>介绍了BeautifulSoup对象的主要属性,通过这些属性可以访 ...
随机推荐
- AndroidのListView之滑动列表项(点击事件和滑动事件共存)
这里正好在项目有这么一个bt的需求,如下图ListView的item可以响应点击事件也可以响应item的左右滑动事件,两个事件可以相互独立互不影响. 听说iphone的list选项就有这样bt的功能, ...
- CSS写表格
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content_Type" content ...
- MQTT的学习研究(十二) MQTT moquette 的 Future API 消息发布订阅的实现
MQTT moquette 的Server发布主题 package com.etrip.mqtt.future; import java.net.URISyntaxException; import ...
- JS-cookie封装
智能社学习笔记 <script type="text/javascript"> /*****设置cookie*****/ function setCookie(name ...
- LeetCode——Product of Array Except Self
Description: Given an array of n integers where n > 1, nums, return an array output such that out ...
- you-get 下载网络上的富媒体信息
You-Get 乃一小小哒命令行程序,提供便利的方式,下载网络上的富媒体信息. 利用you-get下载这个网页的视频: $ you-get http://www.fsf.org/blogs/rms/2 ...
- Scikit Learn安装教程
Windows下安装scikit-learn 准备工作 Python (>= 2.6 or >= 3.3), Numpy (>= 1.6.1) Scipy (>= 0.9), ...
- Javascript一(变量,数据类型,正则表达式,数据,语句)
本文章适合具有一定程序编程语言基础的人士阅读,最好学完Java基础再来阅读本文章更容易理解语言初学者会看起来比较费劲,不易理解 一.导入脚本 在html导入Javascript的格式是: <sc ...
- ClassicLink互通原理
ClassicLink概述_ClassicLink_用户指南_专有网络 VPC-阿里云 https://help.aliyun.com/document_detail/65412.html Class ...
- 程序入口函数和glibc及C++全局构造和析构
分类: CRT Machnasim 2011-06-15 17:45 144人阅读 评论(0) 收藏 举报 c++汇编linuxlist语言编译器 1,程序入口函数和初始化 操作系统在装载可执行文件后 ...