二、爬虫数据解析-bs4

1.BeautifulSoup对象使用 

form bs4 import BeautifulSoup

2.对象的实例化:

  - 1.将本地的html文档中的数据加载到该对象中

    fp = open('./test.html','r',encoding = 'utf-8')
    soup = Beatifulsoup(page_text,'lxml')
    -2.将互联网上获取的页面源码加载到该对象中
       page_text= response.text
       soup = BeatifulSoup(page_text,"lxml")
       

3.提供对象解析的方法和属性:

-1.soup.tagName:返回的是文档中第一次出现的tagName对应的标签
-2.soup.find():
    
    -find('tagName'):等同与soup.div
    -属性定位:soup.find('div',class_/id/attr = 'song')
-3.soup.find_all('tagName'):返回符合要求的所有标签(列表)

4.select方法的用法:

-1.select('某种选择器(id,class,标签,选择器)'),返回一个列表
-2.层级选择器
    -soup.sulect('.tang>ul>a',):>表示的是一个层级
    -soup.select('.tang>ul a'):空格表示多个层级
-3.获取标签之间的文本数据:
    -soup.a.text/string/get_text()
    -text/get_text():可以获取某个标签中所有文本的内容
    -string:只可以获取该标签下面直系的文本内容
-4.获取标签中的属性值:
    -soup.a['href']

 

posted @ 2022-07-31 16:46  机械猿  阅读(47)  评论(0)    收藏  举报