目录
爬虫入门程序
import urllib.request import urllib.error # 定义网址 url="http://www.baidu.com" # 访问网址 responsel=urllib.request.urlopen(url) # 获取响应的状态码 print(responsel.getcode()) # 打印网页的内容长度 print(responsel.read())
爬虫程序添加data,header,然后post请求
import urllib from urllib import request #制定url url="http://www.zhihu.com/signin?next=%2F" #请求头的部分内容:指定浏览器 user_agent="Mozilla/4.0(compatible;MSIE 5.5;Windows NT)" #表单的请求参数 values={'username':"123456",'password':'xxxxxx'} data=urllib.parse.urlencode(values).encode(encodin='utf8') #构建请求头header header={'User-Agent':user_agent} #构建请求 req=request.Request(url,data=data,header=header) #打开网页 resp=request.urlopen(req) #读取网页内容 print(resp.read())
爬虫程序添加cookie
from urllib import request import urllib from http import cookiejar #定义文件名 filename='cookie.txt' #声明MozillaCookieJar对象保存cookie cookie=cookiejar.MozillaCookieJar(filename) #声明一个cookie处理器 handler=request.HTTPCookieProcessor(cookie) #定义处理 opener=request.build_opener(handler) #定义data:帐号+密码 postdata=urllib.parse.urlencode({ 'username':'xxxxx', 'password':'xxxxxxx' }).encode(encoding='UTF8') #登录教务系统的URL loginUrl='http://jwc.hnshzy.cn:90/hnshjw/cas/login.action' #模拟登陆 result=opener.open(loginUrl,postdata) #保存cookie到文件 cookie.save(ignore_discard=True,ignore_expires=True) #利用保存的cookie请求新网站 new_url='http://jwc.hnshzy.cn:90/hnshjw/cas/login.action' #请求新网站 try: result=opener.open(new_url) except request.HTTPError as e: if hasattr(e,'code'): print(e.code) except request.URLError as e: if hasattr(e,'reason'): print(e.reason) else: print(result.read())
正则表达式
import re #定义正则规则=模式,r表示原生字符串 pattern=re.compile(r'hello') #匹配字符 resultl=re.match(pattern,"hello Word") if resultl: print(resultl) result2=re.match(pattern,"hello Word") if result2: print(result2) else: print('no')
#定义正则规则 pattern=re.compile(r'a.c') #匹配 res=re.match(pattern,"abcdefg") print(res) #匹配 . \ pattern2=re.compile(r'a.c') res2=re.match(pattern2,'a.cefg') print(res2) #匹配部分字符 pattern3=re.compile(r'a[a-f,A-F]c') res3=re.match(pattern3,"aDcdefg") print(res3) #匹配数值 pattern4=re.compile(r'a\Dc') res4=re.match(pattern4,"a8cdefghy") print(res4) #匹配空白 pattern5=re.compile(r'a\Sc') res5=re.match(pattern5,'cdefg') print(res5) #匹配个数 pattern6=re.compile(r'abc*') res6=re.match(pattern6,"abccccc") print(res6) #贪婪模式 rexg2=re.compile(r'\w{5,10}?') #匹配 result2=re.match(rexg2,"fajshfw35834hyfgghjgujh") print(result2) #边界 rexg3=re.compile(r'^abc') result3=re.search(rexg3,'abcdefg123') print(result3)
#逻辑分组 rexg4=re.compile(r'abc|efg') result4=re.search(rexg4,'abcoefgdfg') print(result4)