本文主要介绍python爬虫的两大利器:requests和BeautifulSoup库的基本用法。

1. 安装requests和BeautifulSoup库

可以通过3种方式安装:

easy_install
pip
下载源码手动安装

这里只介绍pip安装方式:

pip install requests
pip install BeautifulSoup4

2. requests基本用法示例

# coding:utf-8
import requests

# 下载新浪新闻首页的内容
url = 'http://news.sina.com.cn/china/'
# 用get函数发送GET请求,获取响应
res = requests.get(url)
# 设置响应的编码格式utf-8(默认格式为ISO-8859-1),防止中文出现乱码
res.encoding = 'utf-8'

print type(res)
print res
print res.text

输出:

<class 'requests.models.Response'>
<Response [200]>
<!DOCTYPE html>
<!-- [ published at 2017-04-19 23:30:28 ] -->
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>国内新闻_新闻中心_新浪网</title>
<meta name="keywords" content="国内时政,内地新闻">

下面将上面获取到的网页html内容写入到文件中,这里有一点需要注意的是:python是调用ASCII编码解码程序去处理字符流的,当字符不属于ASCII范围时会抛异常(ordinal not in range(128)),所以要提前设置程序的默认编码:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

然后再将响应的html内容存入文件中:

with open('content.txt','w+') as f:
    f.write(res.text)

3. BeautifulSoup基本用法

1. 自定义测试html

html = '''
<html>
    <body>
        <h1 id="title">Hello World</h1>
        <a href="#link1" class="link">This is link1</a>
        <a href="#link2" class="link">This is link2</a>
    </body>
</html>
'''

2. 从html文本中获取soup

from bs4 import BeautifulSoup
# 这里指定解析器为html.parser(python默认的解析器),指定html文档编码为utf-8
soup = BeautifulSoup(html,'html.parser',from_encoding='utf-8')
print type(soup)

#输出:<class 'bs4.BeautifulSoup'>

3. soup.select()函数用法

(1) 获取指定标签的内容

header = soup.select('h1')
print type(header)
print header
print header[0]
print type(header[0])
print header[0].text

# 输出:
'''
<type 'list'>
[<h1 id="title">Hello World</h1>]
<h1 id="title">Hello World</h1>
<class 'bs4.element.Tag'>
Hello World
'''
alinks = soup.select('a')
print [x.text for x in alinks]

# 输出:[u'This is link1', u'This is link2']

(2) 获取指定id的标签的内容(用'#')

title = soup.select('#title')
print type(title)
print title[0].text

# 输出:
'''
<type 'list'>
Hello World
'''

(3) 获取指定class的标签的内容(用'.')

alinks = soup.select('.link')
print [x.text for x in alinks]

# 输出:[u'This is link1', u'This is link2']

(4) 获取a标签的链接(href属性值)

print alinks[0]['href']

# 输出:#link1

(5) 获取一个标签下的所有子标签的text

body = soup.select('body')[0]
print body.text

# 输出:
'''

Hello World
This is link1
This is link2
'''

(6) 获取不存在的标签

aa = soup.select('aa')
print aa

# 输出:[]

(7) 获取自定义属性值

html2 = '<a href="www.test.com" qoo="123" abc="456">This is a link.</a>'
soup2 = BeautifulSoup(html2,'html.parser')
alink = soup2.select('a')[0]
print alink['qoo']
print alink['abc']

# 输出:
'''
123
456
'''

4. soup.find()和soup.find_all()函数用法

(1) find()和find_all()函数原型:

find和find_all函数都可根据多个条件从html文本中查找标签对象,只不过find的返回对象类型为bs4.element.Tag,为查找到的第一个满足条件的Tag;而find_all的返回对象为bs4.element.ResultSet(实际上就是Tag列表),这里主要介绍find函数,find_all函数类似。

find(name=None, attrs={}, recursive=True, text=None, **kwargs)
注:其中name、attrs、text的值都支持正则匹配。

find_all(name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)
注:其中name、attrs、text的值都支持正则匹配。

(2) find函数的用法示例

html = '<p><a href="www.test.com" class="mylink1 mylink2">this is my link</a></p>'
soup = BeautifulSoup(html,'html.parser')
a1 = soup.find('a')
print type(a1)
# 输出:<class 'bs4.element.Tag'>

print a1.name
print a1['href']
print a1['class']
print a1.text
# 输出:
'''
a
www.test.com
[u'mylink1', u'mylink2']
this is my link
'''
# 多个条件的正则匹配:
import re
a2 = soup.find(name = re.compile(r'w+'),class_ = re.compile(r'mylinkd+'),text = re.compile(r'^this.+link$'))
# 注:这里的class属性之所以写成'class_',是为了防止和python关键字class混淆,其他属性名写正常的名就行,不用这样特殊处理
print a2

# 输出:
'''
<a class="mylink1 mylink2" href="www.test.com">this is my link</a>
'''
# find函数的链式调用
a3 = soup.find('p').find('a')
print a3

# 输出:
'''
<a class="mylink1 mylink2" href="www.test.com">this is my link</a>
'''
# attrs参数的用法
# 注:支持正则匹配属性值(包括自定义属性)
import re
html = '<div class="myclass" my-attr="123abc"></div><div class="myclass" my-attr="abc">'
soup = BeautifulSoup(html,'html.parser')
div = soup.find('div',attrs = {'class':'myclass','my-attr':re.compile(r'd+w+')})
print div

# 输出:
'''
<div class="myclass" my-attr="123abc"></div>
'''

4. 网络爬虫基本架构

5. 补充

1. 代理访问

有时候为了避免封IP,或者在某些公司内网访问外网时候,需要用到代理服务器发送请求,代理的用法示例:

import requests
proxies = {'http':'http://proxy.test.com:8080','https':'http://proxy.test.com:8080'}  # 其中proxy.test.com即为代理服务器的地址
url = 'https://www.baidu.com'  # 这个url为要访问的url
resp = requests.get(url,proxies = proxies)
如果代理服务器需要账号、密码,则可以这样写proxies:

proxies = {'http':'http://{username}:{password}@proxy.test.com:8080','https':'http://{username}:{password}@proxy.test.com:8080'} 

2. 向https的url发送请求

有时候向https的url发送请求会报错:ImportError:no module named certifi.

解决方法:在发送请求时关闭校验:verify = False,如:

resp = requests.get('https://test.com',verify = False)
注:也可通过在headers中传相关鉴权参数来解决此问题。

3. httpbin.org

httpbin.org是requests库的作者开发的一个网站,可以专门用来测试requests库的各种功能,其页面如下:

但httpbin.org的服务器在国外,访问速度比较慢。所以需要在本地搭建一个该网站的镜像,方法如下:

前提:安装好requests库,才能基于该网站测试requests库的功能。

pip install gunicorn httpbin
gunicorn httpbin:app

浏览器输入:127.0.0.1:8000,即可访问。
注:以上步骤在windows下会报错:缺少模块pwd.fcanl,在linux下没问题。

4. requests库官方文档

http://docs.python-requests.org/en/master/

原文链接:

https://www.cnblogs.com/jiayongji/p/7118939.html

-END-


识别图中二维码,领取python全套视频资料

python爬虫系列(2)—— requests和BeautifulSoup的更多相关文章

  1. 爬虫系列(七) requests的基本使用

    一.requests 简介 requests 是一个功能强大.简单易用的 HTTP 请求库,可以使用 pip install requests 命令进行安装 下面我们将会介绍 requests 中常用 ...

  2. Python使用urllib,urllib3,requests库+beautifulsoup爬取网页

    Python使用urllib/urllib3/requests库+beautifulsoup爬取网页 urllib urllib3 requests 笔者在爬取时遇到的问题 1.结果不全 2.'抓取失 ...

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

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

  4. Python爬虫学习三------requests+BeautifulSoup爬取简单网页

    第一次第一次用MarkDown来写博客,先试试效果吧! 昨天2018俄罗斯世界杯拉开了大幕,作为一个伪球迷,当然也得为世界杯做出一点贡献啦. 于是今天就编写了一个爬虫程序将腾讯新闻下世界杯专题的相关新 ...

  5. Python爬虫系列 - 初探:爬取旅游评论

    Python爬虫目前是基于requests包,下面是该包的文档,查一些资料还是比较方便. http://docs.python-requests.org/en/master/ POST发送内容格式 爬 ...

  6. 爬虫基本操作、requests和BeautifulSoup

    1. 爬虫基本操作 例如舆情系统: 获取汽车之家新闻放到自己数据库里,创建自己的app,发布内容,注明来源,自己创业. URL指定内容获取到 - 发送Http请求:http://www.autohom ...

  7. Python爬虫入门——使用requests爬取python岗位招聘数据

    爬虫目的 使用requests库和BeautifulSoup4库来爬取拉勾网Python相关岗位数据 爬虫工具 使用Requests库发送http请求,然后用BeautifulSoup库解析HTML文 ...

  8. Python 爬虫入门(requests)

    相信最开始接触Python爬虫学习的同学最初大多使用的是urllib,urllib2.在那之后接触到了第三方库requests,requests完全能满足各种http功能,真的是好用爆了 :D 他们是 ...

  9. python 爬虫系列教程方法总结及推荐

    爬虫,是我学习的比较多的,也是比较了解的.打算写一个系列教程,网上搜罗一下,感觉别人写的已经很好了,我没必要重复造轮子了. 爬虫不过就是访问一个页面然后用一些匹配方式把自己需要的东西摘出来. 而访问页 ...

随机推荐

  1. Codeforces461A Appleman and Toastman 贪心

    题目大意是Appleman每次将Toastman给他的Ni个数拆分成两部分后再还给Toastman,若Ni == 1则直接丢弃不拆分.而Toastman将每次获得的Mi个数累加起来作为分数,初始时To ...

  2. Android——Bundle savedInstanceState的作用

    写过Android程序的都知道Activity中有一个名称叫onCreate的方法.该方法是在Activity创建时被系统调用,是一个Activity生命周期的开始.可是有一点容易被忽视,就是onCr ...

  3. node.js在2018年能继续火起来吗?我们来看看node.js的待遇情况

    你知道node.js是怎么火起来的吗?你知道node.js现在的平均工资是多少吗?你知道node.js在2018年还能继续火吗?都不知道?那就来看文章吧,多学点node.js,说不定以后的你工资就会高 ...

  4. OS X删除自带的safari和facetime等程序

    打开终端 cd /Applications/ //在应用程序文件目录删除苹果自带的程序 sudo rm -rf Safari.app/ //删除safari浏览器 sudo rm -rf Mail.a ...

  5. 004杰信-关于formSubmit('factorycreate.action','_self')路径的疑惑

    本文材料来源于传智播客,在此说明. 整个项目结构:

  6. error: icpc: Command not found

    交叉编译qt的程序时,出现错误:error: icpc: Command not found. 解决方法,详情查看链接. http://www.cnblogs.com/zengjfgit/p/4744 ...

  7. mysql -- 预处理语句

    所谓预处理,即在真正执行某条SQL语句之前,先将SQL语句准备好,在执行过程中再绑定数据 语法: 准备预处理 prepare 预处理名字 from ‘要执行的SQL语句’ 执行预处理 execute ...

  8. 整理:java定时器。

    本文纯属个人思路,如有错误,请指正. java的Timer依赖Thread,每一个Timer实际上都是一个Thread. import java.util.TimerTask; /** * 本类仅为实 ...

  9. php和js实现文件拖拽上传

    Dropzone.js实现文件拖拽上传 http://www.sucaihuo.com/php/1399.html demo http://www.sucaihuo.com/jquery/13/139 ...

  10. 解决同一页面jQuery多个版本或和其他js库冲突方法

    <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> ...