Python爬虫常用模块

Python标准库——urllib模块

功能:打开URLhttp协议之类
python 3.x中urllib库和urilib2库合并成了urllib库。

其中urllib2.urlopen()变成了urllib.request.urlopen()

urllib2.Request()变成了urllib.request.Request() 

urllib请求返回网页

urllib.request.urlopen

urllib.request.open(url[,data,[timeout,[cafile,[capth[,cadefault,[context]]]]]])

urllib.requset.urlioen可以打开HTTP(主要)、HTTPS、FTP、协议的URL

  • ca 身份验证
  • data 以post方式提交URL时使用
  • url 提交网络地址(全程 前端需协议名 后端需端口 http:/192.168.1.1:80)
  • timeout 超时时间设置

函数返回对象有三个额外的方法

  • geturl() 返回response的url信息 常用与url重定向
  • info()返回response的基本信息
  • getcode()返回response的状态代码
200:success
404:服务器不存在
503:服务器暂停访问
#coding:utf-8
import urllib.request
import time
import platform


#清屏函数(无关紧要 可以不写)
def clear():
    print(u"内容过多 3秒后清屏")
    time.sleep(3)
    OS = platform.system()
    if (OS == u'Windows'):
        os.system('cls')
    else:
        os.system('clear')
#访问函数
def linkbaidu():
    url = 'http://www.baidu.com'
    try:
        response = urllib.request.urlopen(url,timeout=3)
    except urllib.URLError:
        print(u'网络地址错误')
        exit()
    with open('/home/ifeng/PycharmProjects/pachong/study/baidu.txt','w') as fp:
        response = urllib.request.urlopen(url,timeout=3)
        fp.write(response.read())
    print(u'获取url信息,response.geturl()\n:%s'%response.getrul())
    print(u'获取返回代码,response.getcode()\n:%s' % response.getcode())
    print(u'获取返回信息,response.info()\n:%s' % response.info())
    print(u"获取的网页信息经存与baidu.txt")


if __name__ =='main':
    linkbaidu()

Python标准库–logging模块
logging模块能够代替print函数的功能,将标准输出到日志文件保存起来,利用loggin模块可以部分替代debug
re模块
正则表达式
sys模块
系统相关模块

  • sys.argv(返回一个列表,包含所有的命令行)
  • sys.exit(退出程序)


Scrapy框架

urllib和re配合使用已经太落后,现在主流的是Scrapy框架

转载于:https://www.cnblogs.com/oifengo/p/9385950.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值