爬虫基础——刘雯丽

#1.爬虫入门程序

import urllib.request

import urllib.error

#定义网址

url="http://www.baidu.com"

#访问网址

responsel=urllib.request.urlopen(url)

#获取响应码

print(responsel.getcode())

#打印

print(responsel.read())

#2.爬虫程序添加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':"xxxx",'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())

#3.爬虫程序添加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())

#4.正则表达式

import re

# 将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”

pattern = re.compile(r'World')

# 使用re.match匹配文本,获得匹配结果,无法匹配时将返回None

result1 = re.match(pattern,'World')

result2 = re.match(pattern,'World YC!')

result3 = re.match(pattern,'World YC!')

result4 = re.match(pattern,'World YC!')

if result1:

    print(result1)

else:

    print('匹配失败')

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值