Python3.x:bs4解析html基础用法
Python3.x:bs4解析html基础用法
代码:
import urllib.request
from bs4 import BeautifulSoup
import re url = r'http://fund.eastmoney.com/340007.html?spm=search'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
req = urllib.request.Request(url=url, headers=headers)
res = urllib.request.urlopen(req)
html = res.read().decode('utf-8') #使用自带的html.parser解析,速度慢但通用
soup = BeautifulSoup(html, "html.parser")
#或者soup = BeautifulSoup(html, "html5lib")
#输出第一个 title 标签
print(soup.title)
#输出第一个 title 标签的标签名称
print(soup.title.name)
#输出第一个 title 标签的包含内容
print(soup.title.string)
#输出第一个 title 标签的父标签的标签名称
print(soup.title.parent.name)
#输出第一个 p 标签
print(soup.p)
#输出第一个 p 标签的 class 属性内容
print(soup.p['class'])
#输出第一个 a 标签的 href 属性内容
print(soup.a['href'])
#输出第一个 p 标签的所有子节点
print(soup.p.contents)
#输出第一个 a 标签
print(soup.a)
#输出所有的 a 标签,以列表形式显示
print(soup.find_all('a'))
#输出第一个 id 属性等于 gz_gszze 的标签
print(soup.find(id='gz_gszze'))
#输出第一个 id 属性等于 gz_gszze 的标签的文本内容
print(soup.find(id='gz_gszze').get_text())
#获取所有文字内容
print(soup.get_text())
#输出第一个 a 标签的所有属性信息
print(soup.a.attrs)
#循环a标签
for link in soup.find_all('a'):
#获取 link 的 href 属性内容
print(link.get('href')) #对soup.p的子节点进行循环输出
for child in soup.p.children:
print(child) #正则匹配,标签名字中带有sp的标签
for tag in soup.find_all(re.compile("sp")):
print(tag.name)
#按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 class 在Python中是保留字,使用 class 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 class_ 参数搜索有指定CSS类名的tag
#查找dl标签class为dataItem02的所有dl标签
for tag in soup.find_all("dl", class_="dataItem02"):
print(tag.name)
#或者
for tag in soup.find_all('dl', attrs={'class': "dataItem02"}):
print(tag.name)
#查找dl标签class为包含'ui-font-'字符的所有dl标签
for tagspan in child.find_all("span", class_=re.compile('ui-font-')):
print(tagspan.get_text())
#数组对象定义(用于存放对象)
content_list = []
#按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 class 在Python中是保留字,使用 class 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 class_ 参数搜索有指定CSS类名的tag
#查找dl标签class为dataItem02的所有dl标签
for tag in soup.find_all("dl", class_="dataItem02"):
#对tag的子节点进行循环输出
for child in tag.children:
print(child)
#将对象存进数组
content_list.append(child)
#获取数组中的第一个对象的值
print('content_list[0]:'+content_list[0].get_text())
find与find_all一起用:
#第一个class = 'postlist'的div里的所有a 标签是我们要找的信息
#注意:BeautifulSoup()返回的类型是<class 'bs4.BeautifulSoup'>
# find()返回的类型是<class 'bs4.element.Tag'>
# find_all()返回的类型是<class 'bs4.element.ResultSet'>
# <class 'bs4.element.ResultSet'>不能再进项find/find_all操作
all_a = soup.find('div', class_='postlist').find_all('a', target='_blank')
for a in all_a:
title = a.get_text() # 提取文本
if(title != ''):
print("标题:" + title)
#最大页数在span标签中的第10个
pic_max = soup.find_all('span')[10].text #找标题
title = soup.find('h2',class_='main-title').text
#图片地址在img标签alt属性为'图书'地方
pic_url = mess.find('img',alt = '图书')
#获取pic_url中的src属性值:pic_url['src']
html = requests.get(pic_url['src'],headers = headers)
#图片不是文本文件,以二进制格式写入,所以是html.content
#open(路径+文件名,读写模式)
#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
f = open(file_name,'wb')
f.write(html.content)
f.close()
#正则 re.findall 的简单用法(返回string中所有与pattern相匹配的全部字串,返回形式为数组),用法:findall(pattern, string, flags=0)
#示例1:查找全部r标识代表后面是正则的语句
str_1 = re.findall(r"com","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_1)
#输出结果:['com'] #示例2:符号^表示匹配以http开头的的字符串返回,
str_2 = re.findall(r"^http","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_2)
# 输出结果:['http'] #示例3:用$符号表示以html结尾的字符串返回,判断是否字符串结束的字符串
str_3 = re.findall(r"html$","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_3)
# 输出结果:['html'] # 示例4:[...]匹配括号中的其中一个字符
str_4 = re.findall(r"[n,w]b","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_4)
# 输出结果:['nb'] # 示例5:“d”是正则语法规则用来匹配0到9之间的数返回列表
str_5 = re.findall(r"\d","http://www.cnblogs.com/lizm166/p/8143231.html")
str_6 = re.findall(r"\d\d\d","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_5)
# 输出结果:['1', '6', '6', '8', '1', '4', '3', '2', '3', '1']
print (str_6)
# 输出结果:['166', '814', '323'] # 示例6:小d表示取数字0-9,大D表示不要数字,也就是除了数字以外的内容返回
str_7 = re.findall(r"\D","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_7)
# 输出结果:['h', 't', 't', 'p', ':', '/', '/', 'w', 'w', 'w', '.', 'c', 'n', 'b', 'l', 'o', 'g', 's', '.', 'c', 'o', 'm', '/', 'l', 'i', 'z', 'm', '/', 'p', '/', '.', 'h', 't', 'm', 'l'] # 示例7:“w”在正则里面代表匹配从小写a到z,大写A到Z,数字0到9
str_8 = re.findall(r"\w","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_8)
# 输出结果:['h', 't', 't', 'p', 'w', 'w', 'w', 'c', 'n', 'b', 'l', 'o', 'g', 's', 'c', 'o', 'm', 'l', 'i', 'z', 'm', '1', '6', '6', 'p', '8', '1', '4', '3', '2', '3', '1', 'h', 't', 'm', 'l'] # 示例8:“W”在正则里面代表匹配除了字母与数字以外的特殊符号
str_9 = re.findall(r"\W","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_9)
# 输出结果:[':', '/', '/', '.', '.', '/', '/', '/', '.']
# 获取所有a标签(属性target为_blank)
tr.find_all('a',target='_blank')
作者:整合侠
链接:http://www.cnblogs.com/lizm166/p/8205085.html
来源:博客园
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Python3.x:bs4解析html基础用法的更多相关文章
- bs4.BeautifulSoup的基础用法
导入模块 from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html.parser") 下面看下常见的用法 ...
- bs4 解析 以及用法
bs4解析 bs4: 环境安装: lxml bs4 bs4编码流程: 1.实例化一个bs4对象,且将页面源码数据加载到该对象中 2.bs相关的方法或者属性实现标签定位 3.取文本或者取属性 bs的属性 ...
- logstash安装与基础用法
若是搭建elk,建议先安装好elasticsearch 来自官网,版本为2.3 wget -c https://download.elastic.co/logstash/logstash/packag ...
- Smarty基础用法
一.Smarty基础用法: 1.基础用法如下 include './smarty/Smarty.class.php';//引入smarty类 $smarty = new Smarty();//实例化s ...
- asyncio 基础用法
asyncio 基础用法 python也是在python 3.4中引入了协程的概念.也通过这次整理更加深刻理解这个模块的使用 asyncio 是干什么的? asyncio是Python 3.4版本引入 ...
- 【Python爬虫】selenium基础用法
selenium 基础用法 阅读目录 初识selenium 基本使用 查找元素 元素互交操作 执行JavaScript 获取元素信息 等待 前进后退 Cookies 选项卡管理 异常处理 初识sele ...
- 爬虫的三种解析方式(正则解析, xpath解析, bs4解析)
一 : 正则解析 : 常用正则回顾: 单字符: . : 除换行符以外的所有字符 [] : [aoe] [a-w] 匹配集合中任意一个字符 \d : 数字 [0-9] \D : 非数字 \w : 非数字 ...
- python bs4解析网页时 bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to inst(转)
Python小白,学习时候用到bs4解析网站,报错 bs4.FeatureNotFound: Couldn't find a tree builder with the features you re ...
- 爬虫简介、requests 基础用法、urlretrieve()
1. 爬虫简介 2. requests 基础用法 3. urlretrieve() 1. 爬虫简介 爬虫的定义 网络爬虫(又被称为网页蜘蛛.网络机器人),是一种按照一定的规则,自动地抓取万维网信息的程 ...
随机推荐
- 在Win64系统上动态加载无签名驱动:WIN64LUD
1.WIN64LUD的全称是WIN64 Load Unsigned Driver,功能如其名,在WIN64系统上加载无签名的驱动. 2.支持Windows 7/8/8.1/2008R2/2012/20 ...
- codevs 5967 [SDOI2017]相关分析
[题解] /* WA://50分 last:(r-l+1)<-- (r-mid) (r-l+1)<-- (mid-l+1) now:int mid=l+r>>1; tr[l ...
- mysql 安装流程 兼容8.0.0以上版本 解决修改密码规则问题
背景介绍: 第一次安装mysql服务端,版本8.0.6 遇到了问题:1:不知道流程:2:8.0以上版本密码加密规则修改的解决方案: 1:下载mysql 服务端 https://dev.mysql. ...
- object.prototype.call
object.prototype.call /* * object.prototype.call * @ 当一个object没有某个方法,但是其他的有,我们可以借助call或apply用其它对象的方法 ...
- 项目中启动另外的一个app
NSMutableString *webViewContent = [[NSMutableStringalloc] init]; [webViewContent appendString:@" ...
- java实现创建临时文件然后在程序退出时自动删除文件(转)
这篇文章主要介绍了java实现创建临时文件然后在程序退出时自动删除文件,从个人项目中提取出来的,小伙伴们可以直接拿走使用. 通过java的File类创建临时文件,然后在程序退出时自动删除临时文件.下面 ...
- Centos6.8 防火墙设置
1.指令 vi /etc/sysconfig/iptables 添加以下内容和要开放的端口 # Firewall configuration written by system-config-fire ...
- 使用_Capistrano_进行自动化部署(2)
之前的一篇文章是为了解决问题而写的,很多东西都没有介绍清楚,这一篇文章就是完整介绍一下 Capistrano,主要的参考来源是 Modern PHP 这本书. Capistrano 是用于自动部署应用 ...
- 2.06StuModify.aspx(修改姓名,性别,所在班级)
meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title ...
- PL/SQL编程基础(三):数据类型划分
数据类型划分 在Oracle之中所提供的数据类型,一共分为四类: 标量类型(SCALAR,或称基本数据类型) 用于保存单个值,例如:字符串.数字.日期.布尔: 标量类型只是作为单一类型的数据存在,有的 ...