一:知识点

1.安装requests库

  

2.Brautiful soup

  可以提供一些简单的,python式的函数来处理导航,搜索,修改分析树等功能。

  她是一个工具箱,通过解析文档为用户提供需要抓去的数据。

  自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。

  现在是使用Beautiful Soup4,不过现在已经被移植到BS4了,即导入需要导入bs4。

3.导入

  pip install beautifulsoup4

  

4.创建Beautiful Soup对象

  导入bs4库

    from bs4 import BeautifulSoup

  创建:

    soup=BeautifulSoup(html)

5.程序

 import requests
from bs4 import BeautifulSoup
r=requests.get("http://www.baidu.com",headers={'User-Agent':'Mozilla/4.0'})
soup=BeautifulSoup(r.text,"html.parser")
print soup.prettify()

6.打印soup的内容

  print soup.prettify()

7.四大对象种类

  Beautiful Soup将复杂的HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,将所有的对象归纳为四种。

    BeautifulSoup

    Tag

    NavigableString

    Comment

8.BeautifulSoup

  对象表示是一个文档的全部内容,大部分的时候,可以将它当作Tag对象,是一个特殊的Tag,我们可以获取它的类型,名称,以及属性。

  soup.name

  soup.attrs

9.Tag的使用

  找到的是第一个,后面的都没显示。

  soup.title.name

  soup.title.attrs

  soup.meta['content']

  soup.meta.get('content')

 import requests
from bs4 import BeautifulSoup
r=requests.get("http://www.baidu.com",headers={'User-Agent':'Mozilla/4.0'})
soup=BeautifulSoup(r.text,"html.parser")
print soup.title
print soup.meta

效果:

  <title>百度一下,你就知道</title>
  <meta content="text/html;charset=utf-8" http-equiv="content-type"/>

10.NavigableString

  获取标签内部的文字。

  soup.标签名.string

 import requests
from bs4 import BeautifulSoup
r=requests.get("http://www.baidu.com",headers={'User-Agent':'Mozilla/4.0'})
soup=BeautifulSoup(r.text,"html.parser")
print soup.title.string

效果:

  百度一下,你就知道

11.Comment

  是一个特殊类型的NavigableString对象,其实输出的内容仍然不包含注释符号。

12.常用方法(过滤)

  name

  attrs

  text

  limit

  recursive:要不要搜索子孙节点。

  

13.常用方法

  find_all

  find

  .contents     .children

  .descendants

  .string

  .parent

  .next_sibling

  next_elements     .previous_elements

14.程序

 import requests
from bs4 import BeautifulSoup
r=requests.get("http://www.baidu.com",headers={'User-Agent':'Mozilla/4.0'})
soup=BeautifulSoup(r.text,"html.parser")
print soup.script.parent
print soup.title.string

二:案例

1.网址

  https://movie.douban.com/top250?start=0&filter=

  

2.程序

 #encoding=utf-8
import requests
from bs4 import BeautifulSoup
import re
import xlwt #创建全局变量,保存电影信息
dataList=[] #根据地址和开始行获取网页的文本内容
def getHtmlTest(url,startRow):
#头部筛选函数
if(startRow==0):
param={}
else:
param={'start':startRow,'filter':''}
#获取网页
r=requests.get(url,params=param,headers={'User-Agent':'Mozilla/4.0'})
return r.text #创建函数将传入的文本解析获取所需要的数据
def getData(html):
soup=BeautifulSoup(html,'html.parser')
#获取class为grid_view的ol下面的所有列表
movieList=soup.find('ol',attrs={'class':'grid_view'})
#遍历查找内容
for movieLi in movieList.find_all('li'):
data=[]
#获取电影名称
movieHd=movieLi.find('div',attrs={'class':'hd'})
movieName=movieHd.find('span',attrs={'class':'title'}).getText()
data.append(movieName) #电影分数
movieScore=movieLi.find('span',attrs={'class':'rating_num'}).getText()
data.append(movieScore) #电影评价人数
movieEval=movieLi.find('div',attrs={'class':'star'})
movieEvalNum=re.findall(r'\d+',str(movieEval))[-1]
data.append(movieEvalNum) #电影评价
movieQuote=movieLi.find('span',attrs={'class','inq'})
if(movieQuote):
data.append(movieQuote.getText())
else:
data.append("无影评信息") #添加到全局变量中
dataList.append(data)
return #保存到excel
def saveData(savePath):
book=xlwt.Workbook(encoding='utf-8')
sheet=book.add_sheet('前250名的电影信息')
col=(u'电影名称',u'电影评分',u'评论人数',u'短评')
for i in range(0,4):
sheet.write(0,i,col[i])
for i in range(0,250):
data=dataList[i]
for j in range(0,4):
sheet.write(i+1,j,data[j])
book.save(savePath)
return #创建主函数
def mainFunc():
url='https://movie.douban.com/top250'
startRow=0
while startRow<250:
html=getHtmlTest(url,startRow)
getData(html)
startRow += 25
saveData('movieData.xls')
return #测试
mainFunc()

3.效果

  

  

·

005 爬虫(requests与beautifulSoup库的使用)的更多相关文章

  1. $python爬虫系列(2)—— requests和BeautifulSoup库的基本用法

    本文主要介绍python爬虫的两大利器:requests和BeautifulSoup库的基本用法. 1. 安装requests和BeautifulSoup库 可以通过3种方式安装: easy_inst ...

  2. Python爬虫利器:BeautifulSoup库

    Beautiful Soup parses anything you give it, and does the tree traversal stuff for you. BeautifulSoup ...

  3. PYTHON 爬虫笔记五:BeautifulSoup库基础用法

    知识点一:BeautifulSoup库详解及其基本使用方法 什么是BeautifulSoup 灵活又方便的网页解析库,处理高效,支持多种解析器.利用它不用编写正则表达式即可方便实现网页信息的提取库. ...

  4. 利用python的requests和BeautifulSoup库爬取小说网站内容

    1. 什么是Requests? Requests是用Python语言编写的,基于urllib3来改写的,采用Apache2 Licensed 来源协议的HTTP库. 它比urllib更加方便,可以节约 ...

  5. python爬虫系列(2)—— requests和BeautifulSoup

    本文主要介绍python爬虫的两大利器:requests和BeautifulSoup库的基本用法. 1. 安装requests和BeautifulSoup库 可以通过3种方式安装: easy_inst ...

  6. Python爬虫小白入门(三)BeautifulSoup库

    # 一.前言 *** 上一篇演示了如何使用requests模块向网站发送http请求,获取到网页的HTML数据.这篇来演示如何使用BeautifulSoup模块来从HTML文本中提取我们想要的数据. ...

  7. python 3.x 爬虫基础---常用第三方库(requests,BeautifulSoup4,selenium,lxml )

    python 3.x 爬虫基础 python 3.x 爬虫基础---http headers详解 python 3.x 爬虫基础---Urllib详解 python 3.x 爬虫基础---常用第三方库 ...

  8. 爬虫不过如此(python的Re 、Requests、BeautifulSoup 详细篇)

    网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本. 爬虫的本质就是一段自动抓取互联网信息的程序,从网络获取 ...

  9. python爬虫学习(一):BeautifulSoup库基础及一般元素提取方法

    最近在看爬虫相关的东西,一方面是兴趣,另一方面也是借学习爬虫练习python的使用,推荐一个很好的入门教程:中国大学MOOC的<python网络爬虫与信息提取>,是由北京理工的副教授嵩天老 ...

随机推荐

  1. centos7 install python3.7 with problem and how to fix it.

    问题如下: configure: error: no acceptable C compiler found in $PATH 缺少gcc zipimport.ZipImportError: can’ ...

  2. 设置PyCharm中的Python代码模版

    再MacOs运行的PyCharm中,执行python文件,如果不指定python文件字符编码会报错: SyntaxError: Non-ASCII character , but no encodin ...

  3. HDU 2841 容斥 或 反演

    $n,m <= 1e5$ ,$i<=n$,$j<=m$,求$(i⊥j)$对数 /** @Date : 2017-09-26 23:01:05 * @FileName: HDU 284 ...

  4. Web Api问题汇总

    在公网上布署Web Api的时候,不能调用,返回404 在web.config中 Adding the following to the web.config file worked for me: ...

  5. HDU 1717 小数化分数2 数学题

    解题报告:输入一个小于1的小数,让你把这个数转化成分数,但注意,输入的数据还有无限循环的小数,循环节用一对括号包含起来. 之前还没有写过小数转分数的题,当然如果没有循环小数的话,应该比较简单,但是这题 ...

  6. java_环境安装(window10)

    参考地址 下载JDK 下载地址:https://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html 本地环境变 ...

  7. numpy之ones,array,asarray

    from:http://blog.csdn.net/gobsd/article/details/56485177 numpy.ones() 废话少说直接上代码 >>> np.ones ...

  8. Cesium entity click

    var url = 'http://202.107.245.51:81/user/dev/api/v2/sql?rows_per_page=40&page=0&sort_order=a ...

  9. Linux USB驱动学习总结(三)---- USB鼠标的加载、初始化和通信过程

    1.usbmouse的定义:usb鼠标既包含usb设备(usb_device)的属性也包含input输入设备(input_dev)的属性 struct usb_mouse { ];///USB鼠标设备 ...

  10. linux之发送邮件--sendmail服务配置

    新手入门也不知道什么日志分析服务好,鸟哥说logwatch,那我就从logwatch开始吧! logwatch用到了emai发邮件,先从配置邮件发送sendmail开始: 安装sendmail服务,我 ...