python爬虫案例——糗事百科数据采集

来源:互联网 发布:java和php的优缺点 编辑:程序博客网 时间:2024/06/05 15:38

全栈工程师开发手册 (作者:栾鹏)

python教程全解

python爬虫案例——糗事百科数据采集

通过python实现糗事百科页面的内容采集是相对来说比较容易的,因为糗事百科不需要登陆,不需要cookie,不过需要设置http的MIME头,模拟浏览器访问才能正常请求

本案例使用python实现糗事百科数据采集,获取糗事百科热门的文章内容和好评数量。

这里写图片描述

需要安装BeautifulSoup包(点击下载)

python包的安装方法请参考Python库的安装与卸载

python2.7下

#coding:utf-8#本实例用于获取糗事百科热门的文章内容和好评数量。import urllib2import refrom bs4 import BeautifulSoup#糗事百科需要设置MIME头才能正常请求,不需要登陆,也不需要cookieprint('=======================糗事百科数据挖掘==========================')urlstr="https://www.qiushibaike.com/8hr/page/%d"data={}def getdata(html):  #从字符串中安装正则表达式获取值    soup = BeautifulSoup(html, 'html.parser');    alldiv = soup.find_all("div", class_="content")   #内容的外部div    allnum = soup.find_all("span", class_="stats-vote")  #点赞数量的外部span    for i in range(0,len(alldiv)):        print str(alldiv[i].find_all('span')[0]).replace('<span>','').replace('</span>','').replace('<br/>','\r\n').strip()  #内容文字,使用string在文字里还有<br/>时,无法打印,使用text会省略调用<br/>        print allnum[i].find_all('i')[0].string  #好评数量#根据一个网址,获取该网址中符合指定正则表达式的内容def craw(url):    try:        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'        headers = { 'User-Agent' : user_agent }  #设置MIME头,糗事百科对这个进行了验证        request = urllib2.Request(url,headers = headers)  #创建一个请求        response = urllib2.urlopen(request)  #获取响应        html = response.read()  #读取返回html源码        getdata(html)    except urllib2.URLError, e:        if hasattr(e,"code"):            print e.code        if hasattr(e,"reason"):            print e.reasonfor i in range(1,14):    url = urlstr % i    print(url)    craw(url)

python3.6下

#coding:utf-8#本实例用于获取糗事百科热门的文章内容和好评数量。import urllibfrom bs4 import BeautifulSoup#糗事百科需要设置MIME头才能正常请求,不需要登陆,也不需要cookieprint('=======================糗事百科数据挖掘==========================')urlstr="https://www.qiushibaike.com/8hr/page/%d"data={}def getdata(html):  #从字符串中安装正则表达式获取值    soup = BeautifulSoup(html, 'html.parser');    alldiv = soup.find_all("div", class_="content")   #内容的外部div    allnum = soup.find_all("span", class_="stats-vote")  #点赞数量的外部span    for i in range(0,len(alldiv)):        print(str(alldiv[i].find_all('span')[0]).replace('<span>','').replace('</span>','').replace('<br/>','\r\n').strip())  #内容文字,使用string在文字里还有<br/>时,无法打印,使用text会省略调用<br/>        print(allnum[i].find_all('i')[0].string)  #好评数量#根据一个网址,获取该网址中符合指定正则表达式的内容def craw(url):    try:        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'        headers = { 'User-Agent' : user_agent }  #设置MIME头,糗事百科对这个进行了验证        request = urllib.request.Request(url,headers = headers)  #创建一个请求        response = urllib.request.urlopen(request)  #获取响应        html = response.read()  #读取返回html源码        getdata(html)    except urllib.error.URLError as e:        if hasattr(e,"code"):            print(e.code)        if hasattr(e,"reason"):            print(e.reason)for i in range(1,14):    url = urlstr % i    print(url)    craw(url)
原创粉丝点击