Python之数据采集(No.1)

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

猜你喜欢

转载自blog.csdn.net/weixin_42578658/article/details/90044808
今日推荐