【Python网络爬虫】python网络数据采集读书笔记(第一章)

python网络数据采集

第一章 初见网络爬虫

demo1

初次体验,查找python的request模块,只导入一个urlopen函数,然后就可以获取到url所返回的页面中的内容了,这是爬虫的第一步

#python3.x版本
#导入包 查找python的request模块,只导入一个urlopen函数
from urllib.request import urlopen
#打开url
html=urlopen('http://www.baidu.com')
#输出页面内容
print(html.read())

demo2

导入BeautifulSoup,这个库自带对于html格式的解析,只需要对格式进行拆解,就可以得到自己想要得到的内容

#导入beautifulsoup库
from bs4 import BeautifulSoup
from urllib.request import urlopen
html=urlopen('http://www.csdn.net/')
#用bsobj来接收调用BeautifulSoup函数的返回值
bsobj=BeautifulSoup(html.read())
print(bsobj.h2)

demo3

加入异常检测,增加程序的稳定性

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def getTitle(url):
    try:
        html=urlopen(url)
    except HTTPError as e:
        return None
    try:
        bsobj=BeautifulSoup(html.read())
        title=bsobj.body.h1
    except AttributeError as e:
        return None
    return title
if __name__=='__main__':
    url='http://www.hbcnc.edu.cn/Item/101343.aspx'
    title=getTitle(url)
    print(title)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值