为什么要模拟表单提交
现在许多的网站都是需要登录验证后才能访问该网站的页面,爬虫(网络机器人【spider】)该怎么获取这些页面呢!是的,爬虫也是需要登录的,才能获取到后面的页面。
爬虫怎么模拟表单登录
- 复杂的办法,先爬取登录界面,得到登录表单需要的数据
import requests
from bs4 import BeaytifulSoup
def main():
resp = request.get('https://github.com/login')
# 判断服务器返回的状态码是不是200(表示成功)
if resp .status_code != 200:
return
# 获取返回对象里的cookies
cookies = resp.cookies.get_dict()
soup = BeautifulSoup(resp.text,'lxml')
utf_8_value = soup.select_one('form input[name=utf8]').attrs['value']
# 得到csrf
authenticity_token = authenticity_token = soup.select_one('form input[name=authenticity_token]').attrs['value']
# 把提交表单的数据放在字典
data = {
'utf8': utf8_value,
'authenticity_token': authenticity_token,
'login': '1304173787@qq.com',
'password': 'lijin136283',
}
# 发出提交表单的post请求
resp = requests.post('http://github.com/session', data=data,
cookies=cookies)
if __name__ == '__main__':
main()
- 简单的方法,直接用python模块(robobrowser)
pip install robobrowser # 安装模块
import requests
import robobrowser
def mian():
# 获取对象
b = robobrowser.RoboBrowser(parser='lxml')
# 打开表单的网址
b.open('https://github.com/login')
# 获得要提交的哪个表单
f = b.get_form(action='/session')
# 登录的账号
f['login'].value = '1304173787@qq.com'
# 登录的密码
f['password'].value = 'lijin'
# 提交表单
b.submit_form(f)
# 获取提交成功后主页的数据
for a_tag in b.select('a[href]'):
print(a_tag.attrs['href'])
if __name__ == '__main__':
main()
这两个表单的提交都是在没有验证码的情况下实现的。但是现实中,每个网站都为了防止机器提交表单,都有相应的验证码。