Python之爬虫基库

一、request

  1. urlopen()函数的API
urllib. request. urlopen(url, data=None, [ t工『neout, ]*, cafile=None, capath=None, cadefault=False, context=None) 

1.data参数
data参数是可选的。如果要添加参数,并且如果它是字节流编码格式的内容,即bytes类型,则需要通过bytes()方法转化。请求方式不再是GET方式,而是POST方式。

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

2.timeout参数
timeout参数用于设置超时时间,单位为秒,意思就是超过设置时间,没有响应就会报错。

import urllib.error
try:
    response = urllib.request.urlopen('http://www.baidu.com/get',timeout=1)
    print(response.read())
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')
  1. Request
    request参数构造
class urllib. request. Request ( ur 1, data=None, headers={}, origin_req_host=None, unverifiable=False, method=N one) 

URL:用于请求URL,必传参数
data:如果使用data,必须传bytes类型。如果是字典,可以先用urllib.parse模块里的urlencode()编码。
headers:请求头,一般伪装成浏览器
origin_req_host:请求方的host名称或者IP地址。
unverifiable:表示这个请求是否无法验证的,默认是false,换句话说用户没有足够权限来选择接受这个请求的结果。
method:用来请求使用的方法。比如GET,POST和PUT

from urllib import request,parse
url = 'http://httpbin.org/post'
headers = {
    'User-Agent':'Mozilla/4.0',
    'Host':'httpbin.org'
}
dict = {
    'name':'Germey'
}
data = bytes(parse.urlencode(dict),encoding='utf8')
req = request.Request(url=url,data=data,headers=headers,method='POST')
response=request.urlopen(req)
print(response.read().decode('utf-8'))

  1. 代理
from urllib.error import URLError
from urllib.request import ProxyHandler,build_opener
proxy_handler = ProxyHandler({
    'http':'http://127.0.0.1:9743',
    'https':'https:127.0.0.1:9743'
})
opener = build_opener(proxy_handler)
try:
    response = opener.open('https://www.baidu.com')
    print(response.read().decode('utf-8'))
except URLError as e:
    print(e.reason)
  1. Cookies
import http.cookiejar, urllib.request
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name+"="+item.value)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值