本文主要介绍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'mylink\d+'),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>
'''

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的服务器在国外,访问速度比较慢。所以需要在本地搭建一个该网站的镜像,方法如下:

  1. 前提:安装好requests库,才能基于该网站测试requests库的功能。
  2. pip install gunicorn httpbin
  3. gunicorn httpbin:app
  4. 浏览器输入:127.0.0.1:8000,即可访问。

注:以上步骤在windows下会报错:缺少模块pwd.fcanl,在linux下没问题。

4. requests库官方文档

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

python爬虫系列—— requests和BeautifulSoup库的基本用法相关推荐

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

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

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

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

  3. Python爬虫入门四之Urllib库的高级用法

    1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览 ...

  4. 【Python爬虫】requests与urllib库的区别

    我们在使用python爬虫时,需要模拟发起网络请求,主要用到的库有requests库和python内置的urllib库,一般建议使用requests,它是对urllib的再次封装,它们使用的主要区别: ...

  5. python爬虫入门四:BeautifulSoup库(转)

    正则表达式可以从html代码中提取我们想要的数据信息,它比较繁琐复杂,编写的时候效率不高,但我们又最好是能够学会使用正则表达式. 我在网络上发现了一篇关于写得很好的教程,如果需要使用正则表达式的话,参 ...

  6. python爬取小说代码bs4和_使用python爬虫,requests(夹带BeautifulSoup的使用)爬取网络小说...

    由于本人也是初学者,算是小白一枚,这里跟大家分享一下爬取网站上的小说的过程. 第一步我们需要导入我们需要的模块,比如requests,BeautifulSoup,还有正则模块re. 代码如下:impo ...

  7. Python 爬虫---(6) beautifulSoup 库的使用

    其实对很多人来说用起来是不方便的,加上需要记很多规则,所以用起来不是特别熟练,而这节我们提到的beautifulsoup就是一个非常强大的工具,爬虫利器. beautifulSoup "美味 ...

  8. Python 爬虫进阶篇-利用beautifulsoup库爬取网页文章内容实战演示

    我们以 fox新闻 网的文章来举例子,把整篇文章爬取出来. 首先是标题,通过结构可以看出来 class 为 article-header 的节点下的 h1 里的内容即是标题,通过 string 可以获 ...

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

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

最新文章

  1. Tomcat学习总结(3)——Tomcat优化详细教程
  2. WIN 7下绑定网关MAC地址
  3. JavaScript——以简单的方式理解闭包
  4. Java List集合转换相关操作
  5. 原动力CMS PHP域名授权系统V3.0
  6. 用Python玩连连看是什么效果?
  7. 快速设置XMind中的设置联系
  8. 入侵linux_入侵Linux计算机以获得更好的聆听体验
  9. 华为再次重申不造车!谁再言造车,调离岗位
  10. 认识C#中的委托和事件
  11. impala查询数据与hive的查询数据比对(数据的校验)
  12. RESTful API 设计规范
  13. 20200628每日一句
  14. 数据结构之B树查找、插入、删除详解
  15. 金融类自定义View(三)--股票分时图(关于细节和实现思路)
  16. 实用开源镜像站(将持续补全......)
  17. Myeclipse运行servlet文件页面报错404
  18. 网上邻居,详细教您如何打开win7网上邻居
  19. 实战无成本搭建php社工库,简单、高效、几T数据随便查,高效社工库搭建与数据库整理–深夜福利...
  20. ACM入门知识-----ACM赛事介绍

热门文章

  1. 山西民生云大同员认证在什么网_山西民生云大同无法登录
  2. linux磁盘挂载之parted
  3. MFC界面库BCGControlBar v33.0 - 全新升级Ribbon Bar、工具栏等
  4. 派对语音游戏互动平台
  5. 愿十月逝去的人,安好
  6. HBase面试题总结1
  7. flat(),flatMap() 超全详细用法
  8. C语言构造函数和释构函数,c++基础语法:构造函数与析构函数
  9. 分治算法——分金块、求残缺棋盘问题
  10. 520送什么礼物给男朋友比较好?男生最想收到的礼物清单