spider-urllib

Request

请求方式
主要有GET,POST两种类型,另外还有HEAD,PUT,DELETE,OPTIONS等

请求URL
URL全称统一资源定位符,如一个网页文档,一张图片,一个视频等都可以用URL唯一来确定

请求头
包含请求时的头部信息,如User-Agent,Host,Cookies等

请求体
请求时额外附加的数据,如表单提交时的表单数据

Response

1,响应状态码,200,301跳转,404,502服务器内部错误

2,响应头,如内容类型,内容长度,服务器信息,设置Cookie等

3,响应体,最主要的部分,包含求情资源的内容,如网页HTML,图片二进制数据等.

能抓什么数据?

1,网页文本,HTML文档,json格式文件等,

2,图片获取到的是二进制文件,保存为图片格式.

3,视频同为二进制文件,保存为视频格式即可.

4,其他,只要能请求到的都能获取.

解析方式

1,直接处理

2,json解析

3,正则表达式

4,BeautifulSoup

5,Pyquery

6,XPath

为什么我们抓到的数据和浏览器不一样.

js加载

怎么样解决javaScript渲染的问题

分析Ajax请求

Selenium/WebDriver

splash

PyV8,Ghost.py

怎么保存数据

1.文本
纯文本,json,Xml等

2.关系型数据库
如Mysql,Oracle,SQL Server等具有结构化表结构形式存储

3.非关系型数据库
如MongoDB,Redis等key-Value形式存储

4.二进制文件
如图片,视频,音频等等直接保存成特定格式即可

python内置的Http请求库

urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt解析模块

urlopen

import urllib.parse
import urllib.request

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None,
capath=None, cadefault=False, context=None)

response=urllib.request.urlopen(“http:www.baidu.com”)
print(response.read().decode(“utf-8”))

data = bytes(urllib.parse.urlencode({‘word’: ‘hello’}), encoding=’utf8’)
response = urllib.request.urlopen(‘http://httpbin.org/post‘, data=data)
print(response.read())

import socket
import urllib.requset
import urllib.error

try :
response=urllib.requset.urlopen(‘http://httpbin.org/get‘, timeout=0.1”)
except urllib.error.URLError as e:
if isinstance(e.reason,socket.timeout):
print(“TIME OUT”)

响应

响应类型

response=urllib.requset.urlopen(‘http://httpbin.org/get‘)
print(response)

状态码,响应头

response = urllib.request.urlopen(‘https://www.python.org‘)
print(response.status) #状态码
print(response.getheaders())
print(response.getheader(“Server”)) #服务器

Request

request=urllib.request.Request(“https://python.org“)
response=uellib.requset.uelopen(request)
print(response.read().decode(‘utf-8’))

url=’http://httpbin.org/post
headers={ ‘User-Agent’: ‘Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)’,
‘Host’: ‘httpbin.org}
dcit={ ‘name’: ‘Germey’}
data=(perse.urlencode(dcit),encoding=”utf8”)
req=reuest.Request(url=url,data=data,headers=headers,method=’POST’)
reponse=urllib.request.urlopen(req)
print(response.read().decode(‘utf-8’))

url=’http://httpbin.org/post
dcit={ ‘name’: ‘Germey’}
req=request.Request(url=url,data=data.method=’POST’)
req.add_header(“User-Agent”,’Mozilla/4.0 (compatible; MSIE 5.5; Windows NT’)
reponse=urllib.request.urlopen(req)
print(response.read().decode(‘utf-8’))

Handler

代理

import urllib.request

proxy_handler = urllib.request.ProxyHandler({
‘http’: ‘http://127.0.0.1:9743‘,
‘https’: ‘https://127.0.0.1:9743
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open(‘http://httpbin.org/get‘)
print(response.read())

import http.cookiejar, urllib.requestt

获取百度cookie

cookie=http.cookiejar.CookieJar()
handler=urllib.request.HTTPCookieProcessor(cookie)
opener=urllib.request.build_opener(handler)
response=opener.open(“http//ww.baidu.com”)
for item in cookie:
print(item.name+”=”item.value)

保存到火狐格式txt

import http.cookie.jar,urllib.request
filename=”cookie.txt”
cookie=http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener=urllib.request.build_opener(handler)
response=opener.open(‘http://www.baidu.com‘)
cookie.save(ignore_discard=True, ignore_expires=True)

LWP格式保存cookie

import http.cookiejar,urllib.request
filename=”cookie.txt”
cookie=http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener=urllib.request.build_opener(handler)
response=opener.open(‘http://www.baidu.com‘)
cookie.save(ignore_discard=True, ignore_expires=True)

读取LWP

import http.cookiejar,urllib.request
cookie=http.cookiejar.LWPCookieJar()
cookie.load(‘cookie.txt’, ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open(‘http://www.baidu.com‘)
print(response.read().decode(‘utf-8’))

异常处理

from urllib import request, error
try:
response = request.urlopen(‘http://cuiqingcai.com/index.htm‘)
except error.URLError as e:
print(e.reason)#打印异常原因

具体可以捕获哪些异常,URLError和HTTPError

from urllib import request, error

try:
response = request.urlopen(‘http://cuiqingcai.com/index.htm‘)
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep=’\n’)
except error.URLError as e:
print(e.reason)
else:
print(‘Request Successfully’)

import socket
import urllib.request
import urllib.error

try:
response = urllib.request.urlopen(‘https://www.baidu.com‘, timeout=0.01)
except urllib.error.URLError as e:
print(type(e.reason))#查看属性,

URL解析

urlparse #工具模块
urllib.parse.urlparse(urlstring, scheme=”, allow_fragments=True)

from urllib.parse import urlparse

result = urlparse(‘http://www.baidu.com/index.html;user?id=5#comment‘)
print(type(result), result)

六个标准结构,所有的url都可以划分

指定协议类型

from urllib.parse import urlparse

result = urlparse(‘www.baidu.com/index.html;user?id=5#comment’, scheme=’https’)
print(result)
ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html’, params=’user’, query=’id=5’, fragment=’comment’)

fragments的用法

from urllib.parse import urlparse
result = urlparse(‘http://www.baidu.com/index.html;user?id=5#comment‘, allow_fragments=False)
print(result)
ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html’,
params=’user’, query=’id=5#comment’, fragment=”)

from urllib.parse import urlparse
result = urlparse(‘http://www.baidu.com/index.html#comment‘, allow_fragments=False)
print(result)
ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html#comment’, params=”, query=”, fragment=”)

urlunparse

from urllib.parse import urlunparse

data = [‘http’, ‘www.baidu.com’, ‘index.html’, ‘user’, ‘a=6’, ‘comment’]
print(urlunparse(data))

http://www.baidu.com/index.html;user?a=6#comment

urljoin

from urllib.parse import urljoin

print(urljoin(‘http://www.baidu.com‘, ‘FAQ.html’))
print(urljoin(‘http://www.baidu.com‘, ‘https://cuiqingcai.com/FAQ.html‘))
print(urljoin(‘http://www.baidu.com/about.html‘, ‘https://cuiqingcai.com/FAQ.html‘))
print(urljoin(‘http://www.baidu.com/about.html‘, ‘https://cuiqingcai.com/FAQ.html?question=2‘))
print(urljoin(‘http://www.baidu.com?wd=abc‘, ‘https://cuiqingcai.com/index.php‘))
print(urljoin(‘http://www.baidu.com‘, ‘?category=2#comment’))
print(urljoin(‘www.baidu.com’, ‘?category=2#comment’))
print(urljoin(‘www.baidu.com#comment’, ‘?category=2’))

http://www.baidu.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html?question=2
https://cuiqingcai.com/index.php
http://www.baidu.com?category=2#comment
www.baidu.com?category=2#comment
www.baidu.com?category=2

urlencode

from urllib.parse import urlencode

params = {
‘name’: ‘germey’,
‘age’: 22
}
base_url = ‘http://www.baidu.com?’
url = base_url + urlencode(params)
print(url)
http://www.baidu.com?name=germey&age=22

了解

import urllib.robotparser
rp = urllib.robotparser.RobotFileParser()
rp.set_url(“http://www.musi-cal.com/robots.txt“)
rp.read()
rrate = rp.request_rate(“*”)
rrate.requests
3
rrate.seconds
20
rp.crawl_delay(“*”)
6
rp.can_fetch(“*”, “http://www.musi-cal.com/cgi-bin/search?city=San+Francisco“)
False
rp.can_fetch(“*”, “http://www.musi-cal.com/“)
True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值