Python爬虫(bs4)-1

本文基于书籍《Python网络数据采集》(Web Scraping with python)
语言:python3
系统:CentOS7
python库:Beautiful Soup4

安装BeautifulSoup4

登陆官网
https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id5
具体的安装方式

1.使用库BeautifulSoup4

创建BeautifulSoup对象

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = urlopen("你的URL")
bsObj = BeautifulSoup(url)

bsObj 为BeautifulSoup对象
将URL指向HTML/XML文本标签转换成树形层次结构,方便提取

bsObj.标签名

直接调用标签内容

2.异常

URL异常:
无此服务器 ————urlopen返回None
有服务器但服务器无此内容————404 (一个HTTPError错误)
标签异常:
无此标签—————返回None
在无此标签情况下搜索其子标签————AttributeError

异常检测模板:

from urllib.request import urlopen
from urllib.error import HTTPError
def getTitle(url):
    try:
        html = urlopen(url)
    except HTTPError as e:
        return None
    try:
        bsobj = BeautifulSoup(html.read())
        titel = bsobj.boby.h1
    except ArrtibuteError as e:
        return None
title = getTitle("")
if title == None:
    print("Title could not found !")
else:
    print(title)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值