python爬虫基础--获取并解析网页

python爬虫基础–获取并解析网页


引入相关的包

urllib与bs4,是获取和解析网页最常用的库

from urllib.request import urlopen
from bs4 import BeautifulSoup

打开链接

html=urlopen("https://www.datalearner.com/website_navi")

读取网页中的html文档

通过urlopen获得网页对象,将其放入BeautifulSoup中,bsObj存放的目标网页的html文档

bsObj=BeautifulSoup(html.read())
print(bsObj)
学术导航,自定义导航页面 | 学习数据(Datalearner)

BeautifulSoup对象常用的方法

获取到BeautifulSoup对象bsObj后,可以使用bsObj.h1的方式获取html文档中的指定标签,也可以使用BeautifulSoup提供find()findAll()来更加精准的解析标签

findAll(tag, attributes, recursive, text, limit, keywords)
find(tag, attributes, recursive, text, keywords)
  1. tag: html的标签,传入一个列表.findAll({"h1","h2","h3","h4","h5","h6"}),列表中的值为“或”关系
  2. attribute:html标签中的属性,传入一个列表.findAll("span", {"class":{"green", "red"}})
  3. recursive:是否递归标签中的信息,默认为true
  4. text:标签中的文字
  5. limit:相当于find方法
  6. keywords:选择指定属性的标签,与其他属性构成“与”关系
title=bsObj.title
print(title)
<title>学术导航,自定义导航页面 | 学习数据(Datalearner)</title>
title=bsObj.findAll({"title","p"})
if title != None:
    for j in title:
        print(j.get_text())
学术导航,自定义导航页面 | 学习数据(Datalearner)
将本页面设置为主页,登录后可以自定义导航,方便您去其他网站,欢迎使用哦~~~
#注意是class是python保留的关键字
navi_1=bsObj.findAll(class_="col-md-2 text-center")
navi_2=bsObj.findAll("",{"class":"col-md-2 text-center"})
navi_3=bsObj.findAll("div",{"class":"col-md-2 text-center"})
print(len(navi_1))
print(len(navi_2))
print(len(navi_3))
48
48
48
navi=bsObj.findAll(text={"新浪微博","网易云音乐"})
print(navi)
['新浪微博', '网易云音乐', '新浪微博']
imgs=bsObj1.findAll("img")
for img in imgs:
    print(img)
<img class="index-logo-src" height="129" hidefocus="true" src="//www.baidu.com/img/bd_logo1.png" usemap="#mp" width="270"/>
<img class="index-logo-srcnew" height="129" hidefocus="true" src="//www.baidu.com/img/bd_logo1.png?qua=high" usemap="#mp" width="270"/>
<img alt="到百度首页" class="index-logo-src" src="//www.baidu.com/img/baidu_jgylogo3.gif" title="到百度首页"/>
<img alt="到百度首页" class="index-logo-srcnew" src="//www.baidu.com/img/baidu_jgylogo3.gif" title="到百度首页"/>
navi_4=bsObj.findAll(href=["http://weibo.com","http://www.smzdm.com/"],text=["新浪微博","哈哈"])
print(navi_4)
[<a href="http://weibo.com" style="line-height:60px;" target="_blank">新浪微博</a>]

BeautifulSoup对象

  1. BeautifulSoup 对象,用来存放整个html文档
  2. Tag 对象 存放html的子标签
  3. NavigableString 对象,用来表示标签中的文字
  4. Comment 对象,用来查找注释标签,<!--注释-->
html_1=urlopen("http://www.baidu.com")
bsObj1=BeautifulSoup(html_1.read())

处理子标签

childrendecendants()的区别

html_2=urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj=BeautifulSoup(html_2.read())
for child in bsObj.find("table",{"id":"giftList"}).children: 
    print(child)

处理同级别标签

  1. 例子中,将表格的表头去了,任何时候获取一个兄弟标签,都不会包含兄弟标签的本身
  2. 到的是一组标签中的最后一个标签,那么可以使用prevoous_sibling函数
for sibling in bsObj.find("table",{"id":"giftList"}).tr.next_siblings:
    print(sibling)

处理父标签

在爬虫程序中,用到查询父标签的情况较少,查询父标签使用parent

atag=bsObj.find("table",{"id":"giftList"})
print(atag.parent)

猜你喜欢

转载自blog.csdn.net/hfutzhouyonghang/article/details/80672190