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框架

猜你喜欢

转载自blog.csdn.net/weixin_39381833/article/details/80872516