爬虫的简单应用

来源:互联网 发布:网络选修课 编辑:程序博客网 时间:2024/06/03 17:17

这是对 Python网络爬虫与信息提取的一个简单的总结。
在课程中学到的网络爬虫一般分为三个步骤:

网页爬取

这里把给定的url的整个网页代码爬取下来

def getHTMLText(url):    try:        r = requests.get(url, timeout=30)        r.raise_for_status()        r.encoding = r.apparent_encoding        return r.text    except:        return ''

requests.get()

构造一个向服务器请求资源的request对象,返回一个包含服务器资源的Response对象

r.raise_for_status()

在方法内部判断r.status_code是否等于200,不需要增加额外的if语句,该语句便于利用try‐except进行异常处理

r.encoding=r.apparent_encoding

r.encoding探测到headers里面的charset,要注意这里不是页面上指定的charset

r.apparent_encoding如果headers里面发现不了,则会查找网页内容来探测,不过速度很慢

一般使用这段代码可防止爬取的网页因编码格式乱码

对所需信息进行提取

这里一般用到BeatifulSoup或者正则表达式或两者结合、

BeatifulSoup

举个爬取大学排名的例子中的代码

def fillUnivList(ulist, html):    soup = BeautifulSoup(html, 'html.parser')    for tr in soup.find('tbody').children:        if isinstance(tr, bs4.element.Tag):            tds = tr('td')            ulist.append([tds[0].contents[0].string, tds[1].string, tds[3].string])

soup = BeautifulSoup(html, ‘html.parser’)

表示对html,以html.parser解析器进行解析,返回的是一个树状结构的对象,它对应着一个HTML/XML文档的全部内容

soup.find(‘tbody’).children

表示将的所有儿子节点存入列表

tds = tr(‘td’)

把tr中所有td标签内容存入列表

.string

表示标签内非属性字符串

正则表达式

以淘宝搜索商品为例:

def parsePage(ilt, html):    try:        plt = re.findall(r'\"view_price\":\"[\d\.]*\"', html)        tlt = re.findall(r'\"raw_title\":\".*?\"', html)        for i in range(len(plt)):            price = eval(plt[i].split(':')[1])            title = eval(tlt[i].split(':')[1])            ilt.append([price, title])    except:        print("")

两者结合

以股票爬取为例:

def getStockList(lst, stockURL):    html = getHTMLText(stockURL, "GB2312")    soup = BeautifulSoup(html, 'html.parser')    a = soup.find_all('a')    for i in a:        try:            href = i.attrs['href']            lst.append(re.findall(r"[s][hz]\d{6}", href)[0])        except:            continue

这样就完成了信息的提取,下一步是保存在某个文件还是打印了

代码及结果

大学排名

import requestsfrom bs4 import BeautifulSoupimport bs4def getHTMLText(url):    try:        r = requests.get(url, timeout=30)        r.raise_for_status()        r.encoding = r.apparent_encoding        return r.text    except:        return ''def fillUnivList(ulist, html):    soup = BeautifulSoup(html, 'html.parser')    for tr in soup.find('tbody').children:        if isinstance(tr, bs4.element.Tag):            tds = tr('td')            ulist.append([tds[0].contents[0].string, tds[1].string, tds[3].string])def printUnivList(ulist, num):    tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"    print(tplt.format("排名","学校名称","总分",chr(12288)))    for i in range(num):        u=ulist[i]        print(tplt.format(u[0],u[1],u[2],chr(12288)))def main():    uinfo = []    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2017.html'    html = getHTMLText(url)    fillUnivList(uinfo, html)    printUnivList(uinfo, 20)  # 20 univsmain()

大学排名

淘宝搜索

import requestsimport redef getHTMLText(url):    try:        r = requests.get(url, timeout=30)        r.raise_for_status()        r.encoding = r.apparent_encoding        return r.text    except:        return ""def parsePage(ilt, html):    try:        plt = re.findall(r'\"view_price\":\"[\d\.]*\"', html)        tlt = re.findall(r'\"raw_title\":\".*?\"', html)        for i in range(len(plt)):            price = eval(plt[i].split(':')[1])            title = eval(tlt[i].split(':')[1])            ilt.append([price, title])    except:        print("")def printGoodsList(ilt):    tplt = "{:4}\t{:8}\t{:16}"    print(tplt.format("序号", "价格", "商品名称"))    count = 0    for g in ilt:        count = count + 1        print(tplt.format(count, g[0], g[1]))def main():    goods = '书包'    depth = 3    start_url = 'https://s.taobao.com/search?q=' + goods    infoList = []    for i in range(depth):        try:            url = start_url + '&s=' + str(44 * i)            html = getHTMLText(url)            parsePage(infoList, html)        except:            continue    printGoodsList(infoList)main()

淘宝搜索书包

原创粉丝点击