爬虫基础--黄一家

#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('匹配失败')入门程序from urllib import request req = request.Request("http://t.cn/RyhQ2V2")resp = request.urlopen(req)print(resp.read()) reponse=request.urlopen("http://t.cn/RyhQ2V2")#read方法读取网页内容print(reponse.read()) #爬虫添加cookiefrom urllib import  requestfrom  http import cookiejar#定义cookiecookie = cookiejar.CookieJar()#定义一个cookie处理器,把cookie传进去handler=request.HTTPCookieProcessor(cookie)#定义下载器,cookie处理传进去openner=request.build_opener(handler)# 下载页面resp=openner.open("http://t.cn/RyhQ2V2")# 便利cookiefor item in cookie:    print('NAME='+item.name)    print('VALYE'+item.value)    # 模拟登录教务系统from urllib import requestimport urllibfrom http import cookiejar # 定义文件名filename = 'cookie.txt'# 声明MozillaCookieJar对象保存cookiecookie = cookiejar.MozillaCookieJar(filename)# 声明一个cookie处理器handler = request.HTTPCookieProcessor(cookie)# 定义处理opener = request.build_opener(handler)# 定义date:账号+密码postdata = urllib.parse.urlencode({    'username': '202042502021',    'password': '你的密码'}).encode(encoding='UTF8')# 登录教务系统loginUrl='http://t.cn/A66cYMoo# 模拟登录result=opener.open(loginUrl,postdata)# 保存cookie到文件cookie.save(ignore_discard=True,ignore_expires=True) # 利用保存的cookie请求新网址new_url='http://t.cn/A66cYMoo# 请求新网页try:    result=opener.open(new_url)except request.HTTPError as e:    if hasattr(e,'cook'):        print(e.cook)except request.URLError as e :    if hasattr(e,'reason'):        print(e.reason)else:    print(result.read())#正则表达式import re rexp=re.compile(r"\d{5,11}@\w{2}\.\w{3}")# 匹配result=re.match(rexp,'2254969552@qq.com')print(result) # 贪婪模式rexp2=re.compile(r'\w*')# 匹配result2=re.match(rexp2,"ssdshdiuwreiuwhr")print(result2) #边界rexp3=re.compile(r"^dsd$")result3=re.match(rexp3,"abcsdsd123")print(result3) rexp4=re.compile(r"\Aabc")result4=re.match(rexp4,"abcsdsd")print(result4) rexp5=re.compile(r"a\b!bc")result5=re.match(rexp5,"a!bcsdsd")print(result5) rexp6=re.compile(r"abc|efg")result6=re.search(rexp6,"aboefgert")print(result6) rexp7=re.compile(r"(abc){2}")result7=re.search(rexp7,"abcabcfgebs")print(result7) rexp8=re.compile(r"(?P<p1>abc)")result8=re.search(rexp8,"abcefghijk")print(result8) rexp9=re.compile(r"(\d)abc\1")result9=re.search(rexp9,"1abc1")print(result9) rexp10=re.compile(r"(?P<tt>abc)efg(?P=tt)")result10=re.search(rexp10,"abcefgbc")print(result10)[/cp]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值