当前位置: 移动技术网 > IT编程>脚本编程>Python > Python2.7实现模拟登陆-BeautifulSoup的步骤教程

Python2.7实现模拟登陆-BeautifulSoup的步骤教程

2018年04月19日  | 移动技术网IT编程  | 我要评论

南沙群岛的资料,董家会,太原新闻频道直播

我使用的是python2.7版本,windows下操作。所以在写代码之前肯定是要完成python的环境搭建。环境搭建网上也有很多资料,在此我不做多介绍。

1.python实现模拟登陆

loginurl = “https://192.168.1.195/index.php“

1.首先查看loginurl如何实现登陆

在登陆页按下F12,点击network的preserve log(记住一定要点,不然后面找不到自己想要找的东西),输入用户名密码,然后在登陆后的页面找到headers,

这里写图片描述

我们可以看到Form Data即为post提交的数据。有cookie说明我们必须设置cookie处理器来保证cookie,并且访问时必须有user-agent,否则客户端会被屏蔽。

2.python模拟网页登录主要使用urllib,urllib2,cookielib,BeautifulSouup等基本模块,我们需要安装第三方模块。

pip install beautifulsoup4(如果没有安装pip先安装pip)

3.附上我的代码

#coding=utf-8
import urllib
import urllib2
import cookielib
from bs4 import BeautifulSoup
#python2.7实现模拟登陆,爬取图片
class crawl1():
    def __init__(self,opener):
        self.opener=opener
    # 保存图片到本地
    def saveImg(self, link, filename):
        content = self.opener.open(link).read()
        f = open(filename + '.jpg', 'wb')
        f.write(content)
        f.close()
filename="cookie.txt"
#声明一个MozillaCookieJar对象实例来保存cookie,之后写入文件
cookie = cookielib.MozillaCookieJar(filename)
#利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
handler = urllib2.HTTPCookieProcessor(cookie)
#通过handler来构建opener
opener = urllib2.build_opener(handler)
#首页
loginurl = "https://192.168.1.195/index.php"
#登陆前准备:获取action
response = opener.open(loginurl)
soup = BeautifulSoup(response.read(), "lxml")
for input in  soup.form.find_all("input"):
    if input.get("name") == "action":
        action = input.get("value")
#post信息
values = {
        "action":action,
        "login_username":"admin",
        "login_password":"st123456",
    }
postdata = urllib.urlencode(values)
opener.addheaders = [("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")]
#模拟登录,保存cookie到cookie.txt中
result = opener.open(loginurl, postdata)
cookie.save(ignore_discard=True, ignore_expires=True)

2.BeautifulSoup抓取html爬取图片

最开始爬取图片的时候我使用的是re.complie()正则表达式匹配来抓取html,正则表达式着实太麻烦,把我憋了好久,最后终于发现了BeautifulSoup,BeautifulSoup在抓取html上很方便。

附上我的代码,紧接1的代码:

#登陆后我们随意跳转到页面
url = "https://192.168.1.195/plugins/monitor/monitor.php"
result =opener.open(url).read()
soup2=BeautifulSoup(result,'html.parser', from_encoding='utf-8')
length=len(soup2.select(".info"))
furl='https://192.168.1.195'+soup2.select(".info")[6]["href"]
monitor1=opener.open(furl)
#提取图片的链接
soup1=BeautifulSoup(monitor1,'html.parser', from_encoding='utf-8')
monitor2=soup1.select(".graphimage")[0]["id"]
string='a'+monitor2
monitor2='https://192.168.1.195/graph.php?action=view&rra_id=all&local_graph_id='+string
monitor2= monitor2.replace("agraph_","")
 #进入图片页
finresult = opener.open(monitor2).read()
#使用soup解析
soup = BeautifulSoup(finresult, 'html.parser', from_encoding='utf-8')
link2=soup.select(".graphimage")[0]['src']
link3 = 'https://192.168.1.195/' + link2
print link3
#保存在本地的路径
local_path='D:/pycharmProject/pythonspace/test/image/'
#路径+文件名
filename=local_path+str(1)
crawl=crawl1(opener)
crawl.saveImg(link3,filename)
for i in range(2,4):
    link1 = soup.select(".graphimage")[i]['src']
    link='https://192.168.1.195/'+link1
    filename1=local_path+str(i)
    crawl.saveImg(link,filename1)
    print link

以上就是我的总结,有问题的话希望大家多提意见,谢谢

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网