爬虫基础知识

 

目录

 

爬虫入门程序

爬虫程序添加data,header,然后post请求

爬虫程序添加cookie

正则表达式


 

爬虫入门程序

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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值