本文主要介绍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全套视频资料

转载于:https://www.cnblogs.com/IT-Scavenger/p/9883476.html

python爬虫系列(2)—— requests和BeautifulSoup相关推荐

  1. Python爬虫系列06——requests模块(1)

    系列目录 上一篇:05.Python爬虫之正则表达式常用方法(超全) 目录 系列目录 前言 一.浏览器的来源 二.request模块 1.安装request模块 2.get请求和post请求初识 总结 ...

  2. Python爬虫之利用requests,BeautifulSoup爬取小说标题、章节

    爬取雪鹰领主标题和章节内容为列: 查看网页的源代码,如下图所示:  获取html内容部分 import requests headers = {'User-Agent': 'Mozilla/5.0 ( ...

  3. python爬虫系列:xpath爬取图片讲解(零基础向)

    系列文章目录 python爬虫系列:BeautifulSoup爬取小说讲解(零基础向)(版权问题下架) python爬虫系列:requests下载酷我音乐讲解(零基础向)(版权问题下架) 文章目录 目 ...

  4. 「Python爬虫系列讲解」七、基于数据库存储的 BeautifulSoup 招聘爬取

    本专栏是以杨秀璋老师爬虫著作<Python网络数据爬取及分析「从入门到精通」>为主线.个人学习理解为主要内容,以学习笔记形式编写的. 本专栏不光是自己的一个学习分享,也希望能给您普及一些关 ...

  5. python爬取图片教程-推荐|Python 爬虫系列教程一爬取批量百度图片

    Python 爬虫系列教程一爬取批量百度图片https://blog.csdn.net/qq_40774175/article/details/81273198# -*- coding: utf-8 ...

  6. Python爬虫系列之爬取微信公众号新闻数据

    Python爬虫系列之爬取微信公众号新闻数据 小程序爬虫接单.app爬虫接单.网页爬虫接单.接口定制.网站开发.小程序开发 > 点击这里联系我们 < 微信请扫描下方二维码 代码仅供学习交流 ...

  7. python爬虫系列之下载在线文档Excel(腾讯)

    python爬虫系列之腾讯文档Excel数据 一.简介 二.实现步骤 1. 数据准备 2. 获取当前用户nowUserIndex 3.创建导出任务 4. 检查数据准备进度,并下载 三.完整代码 四.效 ...

  8. Python爬虫系列之爬取某社区团微信小程序店铺商品数据

    Python爬虫系列之爬取某社区团微信小程序店铺商品数据 如有问题QQ请> 点击这里联系我们 < 微信请扫描下方二维码 代码仅供学习交流,请勿用于非法用途 数据库仅用于去重使用,数据主要存 ...

  9. 「Python爬虫系列讲解」十四、基于开发者工具 Network 的数据抓包技术

    本专栏是以杨秀璋老师爬虫著作<Python网络数据爬取及分析「从入门到精通」>为主线.个人学习理解为主要内容,以学习笔记形式编写的. 本专栏不光是自己的一个学习分享,也希望能给您普及一些关 ...

  10. 「Python爬虫系列讲解」三、正则表达式爬虫之牛刀小试

    本专栏是以杨秀璋老师爬虫著作<Python网络数据爬取及分析「从入门到精通」>为主线.个人学习理解为主要内容,以学习笔记形式编写的. 本专栏不光是自己的一个学习分享,也希望能给您普及一些关 ...

最新文章

  1. 从未在一起更让人遗憾_我们从未在一起和我们最终没在一起,哪一个更让人难过?...
  2. PaSS: a sequencing simulator for PacBio sequencing PaSS:用于PacBio测序的测序模拟器
  3. python 今日头条 微头条_头条号运营技巧:如何玩转微头条?
  4. Cs Round#56 D Find Path Union
  5. 修改xampp的mysql默认密码
  6. python教程:函数参数中默认值及重要警告
  7. 《数据库系统实训》实验报告——数据库维护
  8. mysql数据库操作指令汇总
  9. 如果我使用Docker,是否需要OpenStack?
  10. html中选择器是什么意思,css中的选择器是什么意思?
  11. block与“阻塞(pend)”与“挂起(suspend)”的区别?
  12. 《人性的弱点全集》- [美]戴尔·卡耐基/著
  13. 139邮箱注册免费注册 html5.mail.10086.cn,139邮箱注册(登录139免费邮箱)
  14. java毕业设计_基于android的二手书城app的设计与实现
  15. (简单)SQL练习13:从titles表获取按照title进行分组
  16. 高等数学上:函数的极限(重难点)
  17. 2021年起重机司机(限桥式起重机)最新解析及起重机司机(限桥式起重机)考试试卷
  18. 中望CAD的lisp编辑器_巧用中望CAD2017自定义工具选项板
  19. NameNode处理上报block块逻辑分析
  20. 国外主流网站分析工具介绍

热门文章

  1. linux挂载磁盘教程
  2. php 重定向不刷新页面,php重定向后跳转不了
  3. Far Cry and Half Life2 Engine scene technique (Dreams_wu原作,转自Sina游戏论坛)
  4. 【nginx负载均衡(四)】nginx的高可用集群利用keepalive实现双vip
  5. Es 查看集群详细信息
  6. 如何将c语言程序封装供python调用_转:用C语言扩展Python的功能
  7. UE4-构建更好的静态网格体
  8. AJAX框架衣柜香薰平价,等我有了新房,卧室也不放“大衣柜”!瞧瞧人家这布置,高级感十足...
  9. 大数据与传统的数据技术,主要有什么差别?
  10. Fabric代码解析第二讲,百度文库