【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)

你可能感兴趣的:(python,url,html,网络爬虫,Python爬虫)