html页面解析类:BeautifulSoup基础使用

本文介绍了使用Bs4库解析HTML的基本方法,包括不同方式的选择器使用,并通过实例展示了如何提取网页中的特定信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bs4:可以解析为lxml格式,也可以解析为html格式

基础使用

#-*-coding:UTF-8-*-

from bs4 import BeautifulSoup
import os,sys
import json
# reload(sys)
# sys.setdefaultencoding('utf8')
if os.path.exists('a.html'):
    print "file not exist!!"
# excelfile='C:\Users\Desktop\get_owner.xls'
# if os.access(excelfile,os.F_OK):
#       os.remove(excelfile)
file=open('a.html','r')
content=file.read()
file.close()

###用bs4解析html网页####
#html=BeautifulSoup(content,'html.parser')  #解析为html的格式
html=BeautifulSoup(content,'lxml')   #解析为lxml的格式
#print html.prettify()  ##格式化输出

######################获取节点的几种方式######3
###节点选择器##
print  html.li  #获取的第一个li节点
print  html.li.attrs  #获取第一个li节点的所有属性 返回字典格式
#print html.li.attrs['href']  #指定属性获取值
print  html.li.a.string  #获取第一个li中a节点的文本内容
print html.li.a.name  #获取节点名

###方法选择器##
print html.find(name='li')#获取的第一个li节点
print html.find(attrs={'href':'a'})#获取第一个属性值匹配的节点
print html.find_all(attrs={'href':'a'})#获取所有属性值匹配的节点
print html.findAll('li',attrs={'href':'a'})

###css选择器##
print html.select('li')
print html.select('li.db p').get_text() #获取class为db的li标签下的p标签
#print html.findAll('li')
print  html.select('#header')
print html.select('.logo')

list=html.select('div li h3 a') #获取div下li下h3节点
for i in list:
    print i
    print i.attrs['href']+'   '+i.string

yield关键字使用

###############yield关键字使用###########
def useyield():
    shuxin = html.select('div li h3 a') #获取div下li下h3节点
    for item in shuxin:
        if 'href' not in item.attrs:  #判断是否有href属性
            continue
        yield {
            'title':item.get('title'),
            'href':item.get('href')
        }
        #yield关键字相当于每组数据都形成一个字典格式,所有字典形成一个对象,返回给调用的函数
        #每解析出来一个数据就返回到i一次

def dictojson(content):
    print json.dumps(content,ensure_ascii=False)  #dumps将字典格式输出为json格式(即字符串),ensure_ascii=False表示接收中文可以用asc码

def usefunc():
    a=useyield()   #
    for i in a:
        print i
        dictojson(i)

usefunc()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值