怎么用python来爬虫_怎么利用Python网络爬虫来提取信息

下面小编就为大家带来一篇Python网络爬虫与信息提取(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

课程体系结构:

1、Requests框架:自动爬取HTML页面与自动网络请求提交

2、robots.txt:网络爬虫排除标准

3、BeautifulSoup框架:解析HTML页面

4、Re框架:正则框架,提取页面关键信息

5、Scrapy框架:网络爬虫原理介绍,专业爬虫框架介绍

理念:The Website is the API …

Python语言常用的IDE工具

文本工具类IDE:

IDLE、Notepad++、Sublime Text、Vim & Emacs、Atom、Komodo Edit

集成工具IDE:

PyCharm、Wing、PyDev & Eclipse、Visual Studio、Anaconda & Spyder、Canopy

·IDLE是Python自带的默认的常用的入门级编写工具,它包含交互式文件式两种方式。适用于较短的程序。

·Sublime Text是专为程序员开发的第三方专用编程工具,可以提高编程体验,具有多种编程风格。

·Wing是Wingware公司提供的收费IDE,调试功能丰富,具有版本控制,版本同步功能,适合于多人共同开发。适用于编写大型程序。

·Visual Studio是微软公司维护的,可以通过配置PTVS编写Python,主要以Windows环境为主,调试功能丰富。

·Eclipse是一款开源的IDE开发工具,可以通过配置PyDev来编写Python,但是配置过程复杂,需要有一定的开发经验。

·PyCharm分为社区版和专业版,社区版免费,具有简单、集成度高的特点,适用于编写较复杂的工程。

适用于科学计算、数据分析的IDE:

·Canopy是由Enthought公司维护的收费工具,支持近500个第三方库,适合科学计算领域应用开发。

·Anaconda是开源免费的,支持近800个第三方库。

Requests库入门

Requests的安装:

Requests库是目前公认的爬取网页最好的Python第三方库,具有简单、简捷的特点。

官方网站:http://www.python-requests.org

在"C:\Windows\System32"中找到"cmd.exe",使用管理员身份运行,在命令行中输入:“pip install requests”运行。

使用IDLE测试Requests库:

>>> import requests

>>> r = requests.get("http://www.baidu.com")#抓取百度页面

>>> r.status_code

>>> r.encoding = 'utf-8'

>>> r.text

1

2

3

4

5

Requests库的7个主要方法

get()方法

r = requests.get(url)

get()方法构造一个向服务器请求资源的Request对象,返回一个包含服务器资源的Response对象。

requests.get(url, params=None, **kwargs)

url:拟获取页面的url链接

params:url中的额外参数,字典或字节流格式,可选

**kwargs:12个控制访问参数

Requests库的2个重要对象

· Request

· Response:Response对象包含爬虫返回的内容

Response对象的属性

r.status_code :HTTP请求的返回状态,200表示连接成功,404表示失败

r.text :HTTP响应内容的字符串形式,即,url对应的页面内容

r.encoding : 从HTTP header中猜测的相应内容编码方式

r.apparent_encoding : 从内容中分析出的相应内容编码方式(备选编码方式)

r.content : HTTP响应内容的二进制形式

r.encoding :如果header中不存在charset,则认为编码为ISO-8859-1 。

r.apparent_encoding :根据网页内容分析出的编码方式可以 看作是r.encoding的备选。

Response的编码:

r.encoding :汇率查询从HTTP header中猜测的响应内容的编码方式;如果header中不存在charset,则认为编码为ISO-8859-1,r.text根据r.encoding显示网页内容

r.apparent_encoding : 根据网页内容分析出的编码方式,可以看作r.encoding的备选

爬取网页的通用代码框架

Requests库的异常

Response的异常

r.raise_for_status() : 如果不是200,产生异常requests.HTTPError;

在方法内部判断r.status_code是否等于200,不需要增加额外的if语句,该语句便于利用try-except进行异常处理

import requests

def getHTMLText(url):

try:

r = requests.get(url, timeout=30)

r.raise_for_status() # 如果状态不是200,引发HTTPError异常

r.encoding = r.apparent_encoding

return r.text

except:

return "产生异常"

if __name__ == "__main__":

url = "http://www.baidu.com"

print(getHTMLText(url))

1

2

3

4

5

6

7

8

9

10

11

12

13

14

通用代码框架,可以使用户爬取网页变得更有效,更稳定、可靠。

HTTP协议

HTTP,Hypertext Transfer Protocol,超文本传输协议。

HTTP是一个基于“请求与响应”模式的、无状态的应用层协议。

HTTP协议采用URL作为定位网络资源的标识。

URL格式:http://host[:port][path]

· host:合法的Internet主机域名或IP地址

· port:端口号,缺省端口号为80

· path:请求资源的路径

HTTP URL的理解:

URL是通过HTTP协议存取资源的Internet路径,一个URL对应一个数据资源。

HTTP协议对资源的操作

理解PATCH和PUT的区别

假设URL位置有一组数据UserInfo,包括UserID、UserName等20个字段。

需求:用户修改了UserName,其他不变。

· 采用PATCH,仅向URL提交UserName的局部更新请求。

· 采用PUT,必须将所有20个字段一并提交到URL,未提交字段被删除。

PATCH的主要好处:节省网络带宽

Requests库主要方法解析

requests.request(method, url, **kwargs)

· method:请求方式,对应get/put/post等7种

例: r = requests.request(‘OPTIONS’, url, **kwargs)

· url:拟获取页面的url链接

· **kwargs:控制访问的参数,共13个,均为可选项

params:字典或字节序列,作为参数增加到url中;

kv = {'key1':'value1', 'key2':'value2'}

r = requests.request('GET', 'http://python123.io/ws',params=kv)

print(r.url)

'''

http://python123.io/ws?key1=value1&key2=value2

'''

1

2

3

4

5

6

data:字典、字节序列或文件对象,作为Request的内容;

json:JSON格式的数据,作为Request的内容;

headers:字典,HTTP定制头;

hd = {'user-agent':'Chrome/10'}

r = requests.request('POST','http://www.yanlei.shop',headers=hd)

1

2

3

cookies:字典或CookieJar,Request中的cookie;

auth:元组,支持HTTP认证功能;

files:字典类型,传输文件;

fs = {'file':open('data.xls', 'rb')}

r = requests.request('POST','http://python123.io/ws',files=fs)

1

2

3

timeout:设定超时时间,秒为单位;

proxies:字典类型,设定访问代理服务器,可以增加登录认证

allow_redirects:True/False,默认为True,重定向开关;

stream:True/False,默认为True,获取内容立即下载开关;

verify:True/False,默认为True,认证SSL证书开关;

cert:本地SSL证书路径

#方法及参数

requests.get(url, params=None, **kwargs)

requests.head(url, **kwargs)

requests.post(url, data=None, json=None, **kwargs)

requests.put(url, data=None, **kwargs)

requests.patch(url, data=None, **kwargs)

requests.delete(url, **kwargs)

1

2

3

4

5

6

7

网络爬虫引发的问题

性能骚扰:

受限于编写水平和目的,网络爬虫将会为web服务器带来巨大的资源开销

法律风险:

服务器上的数据有产权归属,网路爬虫获取数据后牟利将带来法律风险。

隐私泄露:

网络爬虫可能具备突破简单访问控制的能力,获得被保护数据从而泄露个人隐私。

网络爬虫的限制

·来源审查:判断User-Agent进行限制

检查来访HTTP协议头的User-Agent域,值响应浏览器或友好爬虫的访问。

· 发布公告:Roots协议

告知所有爬虫网站的爬取策咯,要求爬虫遵守。

Robots协议

Robots Exclusion Standard 网络爬虫排除标准

作用:网站告知网络爬虫哪些页面可以抓取,哪些不行。

形式:在网站根目录下的robots.txt文件。

案例:京东的Robots协议

http://www.jd.com/robots.txt

# 注释:*代表所有,/代表根目录

User-agent: *

Disallow: /?*

Disallow: /pop/*.html

Disallow: /pinpai/*.html?*

User-agent: EtaoSpider

Disallow: /

User-agent: HuihuiSpider

Disallow: /

User-agent: GwdangSpider

Disallow: /

User-agent: WochachaSpider

Disallow: /

1

2

3

4

5

6

7

8

9

10

11

12

13

Robots协议的使用

网络爬虫:自动或人工识别robots.txt,再进行内容爬取。

约束性:Robots协议是建议但非约束性,网络爬虫可以不遵守,但存在法律风险。

Requests库网络爬虫实战

1、京东商品

import requests

url = "https://item.jd.com/5145492.html"

try:

r = requests.get(url)

r.raise_for_status()

r.encoding = r.apparent_encoding

print(r.text[:1000])

except:

print("爬取失败")

1

2

3

4

5

6

7

8

9

2、亚马逊商品

# 直接爬取亚马逊商品是会被拒绝访问,所以需要添加'user-agent'字段

import requests

url = "https://www.amazon.cn/gp/product/B01M8L5Z3Y"

try:

kv = {'user-agent':'Mozilla/5.0'} # 使用代理访问

r = requests.get(url, headers = kv)

r.raise_for_status()

r.encoding = r.apparent_encoding

print(t.text[1000:2000])

except:

print("爬取失败"

1

2

3

4

5

6

7

8

9

10

11

3、百度/360搜索关键词提交

搜索引擎关键词提交接口

· 百度的关键词接口:

http://www.baidu.com/s?wd=keyword

· 360的关键词接口:

http://www.so.com/s?q=keyword

# 百度

import requests

keyword = "Python"

try:

kv = {'wd':keyword}

r = requests.get("http://www.baidu.com/s",params=kv)

print(r.request.url)

r.raise_for_status()

print(len(r.text))

except:

print("爬取失败")

1

2

3

4

5

6

7

8

9

10

11

# 360

import requests

keyword = "Python"

try:

kv = {'q':keyword}

r = requests.get("http://www.so.com/s",params=kv)

print(r.request.url)

r.raise_for_status()

print(len(r.text))

except:

print("爬取失败")

1

2

3

4

5

6

7

8

9

10

11

4、网络图片的爬取和存储

网络图片链接的格式:

http://www.example.com/picture.jpg

国家地理:

http://www.nationalgeographic.com.cn/

选择一张图片链接:

http://image.nationalgeographic.com.cn/2017/0704/20170704030835566.jpg

图片爬取全代码

import requests

import os

url = "http://image.nationalgeographic.com.cn/2017/0704/20170704030835566.jpg"

root = "D://pics//"

path = root + url.split('/')[-1]

try:

if not os.path.exists(root):

os.mkdir(root)

if not os.path.exists(path):

r = requests.get(url)

with open(path,'wb') as f:

f.write(r.content)

f.close()

print("文件保存成功")

else:

print("文件已存在")

except:

print("爬取失败")

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

5、IP地址归属地的自动查询

www.ip138.com IP查询

http://ip138.com/ips138.asp?ip=ipaddress

http://m.ip138.com/ip.asp?ip=ipaddress

import requests

url = "http://m.ip138.com/ip.asp?ip="

ip = "220.204.80.112"

try:

r = requests.get(url + ip)

r.raise_for_status()

r.encoding = r.apparent_encoding

print(r.text[1900:])

except:

print("爬取失败")

1

2

3

4

5

6

7

8

9

10

# 使用IDLE

>>> import requests

>>> url ="http://m.ip138.com/ip.asp?ip="

>>> ip = "220.204.80.112"

>>> r = requests.get(url + ip)

>>> r.status_code

>>> r.text

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值