ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python爬虫——使用urllib爬取网页

2021-11-26 21:00:16  阅读:156  来源: 互联网

标签:python request urllib 爬取 url data response urlopen


1.urlib库是python内置的http请求库,它可以看作处理url的组件集合。urllib库包含4大模块:

(1)urllib.request:请求模块

(2)urllib.error: 异常处理模块

(3)urllib.parse:URL解析模块

(4)urllib.robotparser:robots.txt解析模块

下面是用urllib库爬取百度首页

import urllib.request  # 导入urllib的请求模块request

url = "http://www.baidu.com"
response = urllib.request.urlopen(url)  # 调用urllib.request库的urlopen()方法打开网址
html = response.read().decode("utf-8")  # 使用read()方法读取爬到的内容,并以utf-8方式编码
print(response.status)  # 打印响应的状态码
print(html)

以上代码打印出来就可以看到我们把百度首页的网页源码全部爬下来了

2.分析urlopen()方法

urlopen()可以接受多个参数,该方法的定义如下:

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

上述方法的定义中的详细参数介绍如下:

(1)url:url地址的字符串,也可以是一个urllib.request对象

(2)data:必须是一个bytes对象;data必须符合它的标准格式,使用urllib.parse.urlencode()可以将自定义的data转换为标准格式,当用设置了data参数时,需要将请求改为post请求;当没有设置时以get方式请求。

(3)timeout:该参数用于设置超时时间,单位为秒。

  (4)cafile/capath/cadefault:用于实现可信任的CA证书的HTTPS请求

(5)context:用于实现SSL加密传输

data参数的使用实例:

import urllib.request
import urllib.parse
url = "http://httpbin.org/post"  # 这个网站可以测试post请求
data = {"word": "hello"}
datas = bytes(urllib.parse.urlencode(data).encode("utf-8"))
response = urllib.request.urlopen(url, data=datas)
print(response.read())

打印结果如下:

"{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "word": "hello"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Content-Length": "10", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.6", 
    "X-Amzn-Trace-Id": "Root=1-61a0d4a8-7d86e6c70769eacc767cc4ce"
  }, 
  "json": null, 
  "origin": "111.2.154.24", 
  "url": "http://httpbin.org/post"
}
"

timeout参数的使用示例:

import urllib.request
url = "http://httpbin.org/get"
response = urllib.request.urlopen(url, timeout=0.1)
print(response.read())

运行结果报错:During handling of the above exception, another exception occurred:

urllib.error.URLError: <urlopen error timed out>

这里我们设置超时时间是0.1秒,程序0.1秒过后,服务器没有响应,于是报错了,错误原因是请求超时。

标签:python,request,urllib,爬取,url,data,response,urlopen
来源: https://blog.csdn.net/w_sunset/article/details/121567399

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有