python爬虫登录
A. 怎样用python设计一个爬虫模拟登陆知乎
两种方法:
1.带cookielib和urllib2
import urllib2
import urllib
import cookielib
def login():
email = raw_input("请输入用户名:")
pwd = raw_input("请输入密码:") data={"email":email,"password":pwd}
post_data=urllib.urlencode(data) cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))headers
={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}website =
raw_input('请输入网址:')req=urllib2.Request(website,post_data,headers)content=opener.open(req)print
content.read()
2.使用selenium
import selenium import webdriver
browser=webdriver.Firefox()
browser.get("Url")
browser.find_element_by_id(" ").sendkey("username")
browser.find_element_by_id(" ").sendkey("pass")
browser.find_element_by_id(" ").click()
其实我这个最简单了,用的python3,requests, 只需要验证一次,就会保存cookies,下次登录使用cookies登录。
第一步、打开首页获取_xref值,验证图片 第二步、输入账号密码 第三步、看是否需要验证、要则下载验证码图片,手动输入
第四步、判断是否登录成功、登录成功后获取页面值。
B. python爬虫登录知乎后怎样爬取数据
模拟登录
很多网站,比如知乎、微博、豆瓣,都需要登录之后,才能浏览某些内容。所以想要爬取这类网站,必须先模拟登录。比较简单的方式是利用这个网站的 cookie。cookie 相当于是一个密码箱,里面储存了用户在该网站的基本信息。在一次登录之后,网站会记住你的信息,把它放到cookie里,方便下次自动登录。所以,要爬取这类网站的策略是:先进行一次手动登录,获取cookie,然后再次登录时,调用上一次登录得到的cookie,实现自动登录。
动态爬取
在爬取知乎某个问题的时候,需要将滑动鼠标滚轮到底部,以显示新的回答。静态的爬取方法无法做到这一点,可以引入selenium库来解决这一问题。selenium库模拟人浏览网站、进行操作,简单易懂。
C. python 爬虫如何实现cnki 的自动ip登录
自己做个代理服务器。例如618爬虫代理,再指向次一级代理。或者是直接让爬虫通过http proxy的参数设置去先把一个代理。 代理池通常是租来的,或者是扫描出来的。扫描出来的往往大部分都不可用。 爬虫的实现有几百种方案。通常建议直接从SCRAPY入手。
D. python爬虫模拟登陆网站
你可以结合使用requests和selenium这两个python模块来实现半自动化模拟登录。
#-*-coding:utf-8-*-
importtime
importrequests
fromrequests.sessionsimportcookiejar_from_dict
fromseleniumimportwebdriver
LOGIN_URL='http://www.cofool.com/'
driver=webdriver.Firefox()
driver.get(LOGIN_URL)
time.sleep(30)
cookies={}
forcookieindriver.get_cookies():
cookies[cookie['name']]=cookie['value']
driver.quit()
printcookies
#cookies={}
headers={
'User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64;rv:24.0)Gecko/20100101Firefox/24.0',
'Accept':'*/*',
'Connection':'keep-alive',
}
cookies=cookiejar_from_dict(cookies)
rep=requests.get('http://www2.cofool.com/stock/mainzjgp.asp',cookies=cookies,headers=headers)
printrep.text
如果解决了您的问题请采纳!
如果未解决请继续追问
E. 怎样用Python设计一个爬虫模拟登陆知乎
给你一个例子,可以看看:
import requests
import time
import json
import os
import re
import sys
import subprocess
from bs4 import BeautifulSoup as BS
class ZhiHuClient(object):
"""连接知乎的工具类,维护一个Session
2015.11.11
用法:
client = ZhiHuClient()
# 第一次使用时需要调用此方法登录一次,生成cookie文件
# 以后可以跳过这一步
client.login("username", "password")
# 用这个session进行其他网络操作,详见requests库
session = client.getSession()
"""
# 网址参数是账号类型
TYPE_PHONE_NUM = "phone_num"
TYPE_EMAIL = "email"
loginURL = r"http://www.hu.com/login/{0}"
homeURL = r"http://www.hu.com"
captchaURL = r"http://www.hu.com/captcha.gif"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Host": "www.hu.com",
"Upgrade-Insecure-Requests": "1",
}
captchaFile = os.path.join(sys.path[0], "captcha.gif")
cookieFile = os.path.join(sys.path[0], "cookie")
def __init__(self):
os.chdir(sys.path[0]) # 设置脚本所在目录为当前工作目录
self.__session = requests.Session()
self.__session.headers = self.headers # 用self调用类变量是防止将来类改名
# 若已经有 cookie 则直接登录
self.__cookie = self.__loadCookie()
if self.__cookie:
print("检测到cookie文件,直接使用cookie登录")
self.__session.cookies.update(self.__cookie)
soup = BS(self.open(r"http://www.hu.com/").text, "html.parser")
print("已登陆账号: %s" % soup.find("span", class_="name").getText())
else:
print("没有找到cookie文件,请调用login方法登录一次!")
# 登录
def login(self, username, password):
"""
验证码错误返回:
{'errcode': 1991829, 'r': 1, 'data': {'captcha': '请提交正确的验证码 :('}, 'msg': '请提交正确的验证码 :('}
登录成功返回:
{'r': 0, 'msg': '登陆成功'}
"""
self.__username = username
self.__password = password
self.__loginURL = self.loginURL.format(self.__getUsernameType())
# 随便开个网页,获取登陆所需的_xsrf
html = self.open(self.homeURL).text
soup = BS(html, "html.parser")
_xsrf = soup.find("input", {"name": "_xsrf"})["value"]
# 下载验证码图片
while True:
captcha = self.open(self.captchaURL).content
with open(self.captchaFile, "wb") as output:
output.write(captcha)
# 人眼识别
print("=" * 50)
print("已打开验证码图片,请识别!")
subprocess.call(self.captchaFile, shell=True)
captcha = input("请输入验证码:")
os.remove(self.captchaFile)
# 发送POST请求
data = {
"_xsrf": _xsrf,
"password": self.__password,
"remember_me": "true",
self.__getUsernameType(): self.__username,
"captcha": captcha
}
res = self.__session.post(self.__loginURL, data=data)
print("=" * 50)
# print(res.text) # 输出脚本信息,调试用
if res.json()["r"] == 0:
print("登录成功")
self.__saveCookie()
break
else:
print("登录失败")
print("错误信息 --->", res.json()["msg"])
def __getUsernameType(self):
"""判断用户名类型
经测试,网页的判断规则是纯数字为phone_num,其他为email
"""
if self.__username.isdigit():
return self.TYPE_PHONE_NUM
return self.TYPE_EMAIL
def __saveCookie(self):
"""cookies 序列化到文件
即把dict对象转化成字符串保存
"""
with open(self.cookieFile, "w") as output:
cookies = self.__session.cookies.get_dict()
json.mp(cookies, output)
print("=" * 50)
print("已在同目录下生成cookie文件:", self.cookieFile)
def __loadCookie(self):
"""读取cookie文件,返回反序列化后的dict对象,没有则返回None"""
if os.path.exists(self.cookieFile):
print("=" * 50)
with open(self.cookieFile, "r") as f:
cookie = json.load(f)
return cookie
return None
def open(self, url, delay=0, timeout=10):
"""打开网页,返回Response对象"""
if delay:
time.sleep(delay)
return self.__session.get(url, timeout=timeout)
def getSession(self):
return self.__session
if __name__ == '__main__':
client = ZhiHuClient()
# 第一次使用时需要调用此方法登录一次,生成cookie文件
# 以后可以跳过这一步
# client.login("username", "password")
# 用这个session进行其他网络操作,详见requests库
session = client.getSession()
F. Python爬虫模拟登陆
你首先要了解登录的过程是什么
先要利用头来模拟伪装成浏览器访问网站
post是把数据发送给网站后台,get就相反(一般是这种情况)
把post的数据也做成一样的样式
访问网站,如果是200,则表示成功了
最后你可以使用bs4之类的,根据正则匹配获取相关的数据或者下载保存到本地
G. python 爬虫怎么模拟登录
首先抓包查看登录过程,找出登录验证方法,有的是登录接口返回token,将token置于头部,有的是靠cookie验证
之后使用requests包模拟登录过程
req = requests.post(url=登录接口, data=参数, headers=请求头)
token的话获取req.content自己截出来
cookie的话使用req.cookies
在之后的过程中,如需要cookie
req = requests.post(url=数据接口, data=参数, headers=请求头, cookies=刚才的cookie)
H. 怎么用python爬虫实现自动登录电信chinanet的无线认证平台
前几天女朋友跟我说,她在一个素材网站上下载东西,积分总是不够用,积分是怎么来的呢,是每天登录网站签到获得的,当然也能购买,她不想去买,因为偶尔才会用一次,但是每到用的时候就发现积分不够,又记不得每天去签到,所以就有了这个纠结的事情。怎么办呢,想办法呗,于是我就用python写了个小爬虫,每天去自动帮她签到挣积分。废话不多说,下面就讲讲代码。
我这里用的是python3.4,使用python2.x的朋友如果有需要请绕道查看别的文章。
工具:Fiddler
首先下载安装Fiddler,这个工具是用来监听网络请求,有助于你分析请求链接和参数。
I. python爬虫网站的登录url怎么找
抓取网页所有url的简单Python爬虫源码,只用到了一个Python标准库urllib模块,没有用BeautifulSoup第三方库。python 多线程爬虫是一个很实用的工具。
Python爬虫源码发,如下:
import urllib
content = urllib.urlopen('http://www.iplaypython.com/').read()
s1=0
while s1>=0:
begin = content.find(r'<a',s1) m1="content.find(r'" href=",begin)
m2 = content.find(r">',m1)
s1 = m2
if(begin<=0):
break
elif(content[m1:m2].find(r" ")!=-1):
m2 = content[m1:m2].find(r' ')
url = content[m1+6:m1+m2-1]
print url
elif m2>=0:
url = content[m1+6:m2-1]
print url
print "end."
</a',s1)>
J. python爬虫模拟登录是什么意思
有些网站需要登录后才能爬取所需要的信息,此时可以设计爬虫进行模拟登录,原理是利用浏览器cookie。
一、浏览器访问服务器的过程:
(1)浏览器(客户端)向Web服务器发出一个HTTP请求(Http request);
(2)Web服务器收到请求,发回响应信息(Http Response);
(3)浏览器解析内容呈现给用户。
二、利用Fiddler查看浏览器行为信息:
Http请求消息:
(1)起始行:包括请求方法、请求的资源、HTTP协议的版本号
这里GET请求没有消息主体,因此消息头后的空白行中没有其他数据。
(2)消息头:包含各种属性
(3)消息头结束后的空白行
(4)可选的消息体:包含数据
Http响应消息:
(1)起始行:包括HTTP协议版本,http状态码和状态
(2)消息头:包含各种属性
(3)消息体:包含数据
可以发现,信息里不仅有帐号(email)和密码(password),其实还有_xsrf(具体作用往后看)和remember_me(登录界面的“记住我”)两个值。
那么,在python爬虫中将这些信息同样发送,就可以模拟登录。
在发送的信息里出现了一个项:_xsrf,值为
这个项其实是在访问知乎登录网页https://www.hu.com/#signin时,网页发送过来的信息,在浏览器源码中可见:
所以需要先从登录网址https://www.hu.com/#signin获取这个_xsrf的值,
并连同帐号、密码等信息再POST到真正接收请求的http://www.hu.com/login/email网址。
(2)获取_xsrf的值:
爬取登录网址https://www.hu.com/#signin,从内容中获取_xsrf的值。
正则表达式。
(3)发送请求:
xsrf = 获取的_xsrf的值
data = {"email":"xxx","password":"xxx","_xsrf":xsrf}
login = s.post(loginURL, data = data, headers = headers)
loginURL:是真正POST到的网址,不一定等同于登录页面的网址;
(4)爬取登录后的网页:
response = s.get(getURL, cookies = login.cookies, headers = headers)
getURL:要爬取的登陆后的网页;
login.cookies:登陆时获取的cookie信息,存储在login中。
(5)输出内容:
print response.content
五、具体代码:
[python]view plain
#-*-coding:utf-8-*-
#author:Simon
#updatetime:2016年3月17日17:35:35
#功能:爬虫之模拟登录,urllib和requests都用了...
importurllib
importurllib2
importrequests
importre
headers={'User-Agent':'Mozilla/5.0(WindowsNT6.2)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.12Safari/535.11'}
defget_xsrf():
firstURL="http://www.hu.com/#signin"
request=urllib2.Request(firstURL,headers=headers)
response=urllib2.urlopen(request)
content=response.read()
pattern=re.compile(r'name="_xsrf"value="(.*?)"/>',re.S)
_xsrf=re.findall(pattern,content)
return_xsrf[0]
deflogin(par1):
s=requests.session()
afterURL="https://www.hu.com/explore"#想要爬取的登录后的页面
loginURL="http://www.hu.com/login/email"#POST发送到的网址
login=s.post(loginURL,data=par1,headers=headers)#发送登录信息,返回响应信息(包含cookie)
response=s.get(afterURL,cookies=login.cookies,headers=headers)#获得登陆后的响应信息,使用之前的cookie
returnresponse.content
xsrf=get_xsrf()
print"_xsrf的值是:"+xsrf
data={"email":"xxx","password":"xxx","_xsrf":xsrf}
printlogin(data)
六、补充:
用知乎网做完试验,发现这里好像并不需要发送_xsrf这个值。
不过有的网站在登陆时确实需要发送类似这样的一个值,可以用上述方法。