Python之数据采集(No.1)

本文介绍了Python数据采集的基本操作,包括利用urllib进行网络请求,使用BeautifulSoup解析HTML内容。讲解了初始化Python文件、处理HTTP错误、通过class属性查找元素可能遇到的问题,以及BeautifulSoup中不同类型的对象,如Tag、NavigableString和Comment。同时阐述了子标签、后代标签及父标签的关系,以及如何处理兄弟标签和父标签。

1.初建python文件时,会默认生成下面文件
在这里插入图片描述
–init–文件的作用是构造函数或者初始化程序

2.urlib是Python的标准库,包含从网络请求数据,处理cookie,改变像请求头,用户代理这些元数据的函数,同时它也可以用来打开并读取一个从网络获取的远程对象

3.BeautifulSoup库中最常用的就是BeautifulSoup对象(html后面的read方法可有可无)

from urllib.request import urlopen
from bs4 import BeautifulSoup
html=urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj=BeautifulSoup(html.read())
print(bsObj.h1)

运行结果

<h1>An Interesting Title</h1>

加入检查与错误处理的代码

from urllib.request import urlopen
from  urllib.error import HTTPError,URLError
from bs4 import BeautifulSoup
def getTitle(url):
    try:
        html=urlopen(url)
    except(HTTPError,URLError) as e:
        return  None
    try:
        bsObj=BeautifulSoup(html.read())
        title=bsObj.body.h1
    except AttributeError as e:
        return  None
    return title
title=getTitle("http://www.baidu.com")
if title==None:
    print("Title could not be found")
else:
    print(title)

检查由于URL,HTTP引起的错误

4.findall抽取包含在< span class=“green”></ span>中的文字(get_text()方法去掉标签以及超链接,段落等)


from  urllib.error import HTTPError,URLError
from bs4 import BeautifulSoup
def getName(url):
    try:
        html=urlopen(url)
    except(HTTPError,URLError) as e:
        return  None
    try:
        bsObj=BeautifulSoup(html)
        nameList=bsObj.findAll("span",{"class":"green"})
        for name in nameList:
            print(name.get_text())
    except AttributeError as e:
        return  None
    return
getName("http://www.pythonscraping.com/pages/warandpeace.html")
findAll(tag,attributes,recursive,text,limit,keywords)
find(tag,attributes,recursive,text,keywords)

find函数等价于findall函数的limit等于1的情景
针对上述按列,printf(len(namelist)),findall 返回的是42,find返回的是1

.findAll("span",{"class":{"green","red"}})
alltext=bsobj.findall(id="text")

6.class 属性查找可能会出错,因为class 同时是python中的保留字

bsObj.findAll(class="green")替换成
bsObj.findAll("",{"class":"green"})

7.BeautifulSoup

  • BeautifulSoup对象
  • 标签Tag对象
  • NavigableString对象
  • Comment对象
    8.不是所有的后代标签都是子标签,但是所有的子标签都是后代标签
    9.处理兄弟标签
bsobj.find("table",{"id":"giftList"}).tr.next_siblings/previous_siblings返回集合
next_sibling/previous_sibling返回单个标签

10.父标签处理:parents或者parent

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值