layuiajax提交表单控制层代码_Python:表单交互与模拟登陆

16bb8c52b15dce8ebd0f7cba81359249.gif

       前面我们又介绍过简单网页和复杂的异步加载网页爬取过程,其实都是通过请求URL网址来获取信息的,但是现在很多网站都需要登录后才能得到信息,这时改如何处理呢?

今天我们来介绍通过观查表单源代码和逆向工程来推导出表单信息,来填写表单以获取网页信息,同时通过提交Cookie信息来模拟登录网站。

1、表单交互

import requestsparams={  ‘key1’:’value1’,  ‘key2’:’value2’,  ‘key3’:’value3’}html=requests.post(url,data=params)print(html.text)

        由于现在大多数网站都有多种登录方式,通过短信或者微信登录等,相对通过直接调用表单进行交互已经比较麻烦,这里不做详细介绍,主要表单交互可以通过登录后来找到对应的网页,见下文。

2、逆向工程如何构建表单

对于登录后使用了异动加载的网页,可以通过逆向工程构架你表单来找到不同的网页信息,下面我们先看一下如何构建表单。

(1)登录拉勾网,打开Chrome浏览器,选择Netwoek

(2)搜索关键字python得到post的表单信息见下图一和下图二

图一

2663313574ec0a8ba634760261921165.png

图二

a54edb8e05a477684600442b640843c1.png

3、Cookie模拟登录

        有时候表单字段可能通过加密或者其它形式的包装进行构建,这样就比较困难和麻烦,因此,这时候就有必要选择通过提交Cookie信息进行模拟登录会方便很多。

什么是Cookie?

Cookie是指某些网站为了辨别用户身份、进行session跟踪而存储在用户本地终端上的数据。一般互联网和电商都是通过跟踪Cookie来作为识别用户的唯一标识的。

可见Cookie是带有用户信息的,因此才可以通过Cookie来模拟登陆网站。

继续通过拉勾网如下图可以看到cookie如下:

36fab61383cc684f29d854d3273436d8.png

通过代码:

import requestsurl='https://www.lagou.com'headers={   'cookie': 'xxx‘}html=requests.get(url,headers=headers)print(html.text)

得到登陆后的网页源码内容:

be171b38db4e825841db3d79b42fd16d.png

4、案例实践:爬取拉勾网招聘信息

拉勾网结合了异步加载技术和提交表单,让我们来分析一下此网站。

分析思路:

(1)登陆打开拉勾网站,页面如下,搜索关键字:大数据

398e70367aa53610cd405a8f9e2928a8.png

(2)通过观察,网页元素不在网页源代码中,说明使用了异步加载技术。

af5e042c99d78e326f79ee59894dbb33.png

(3)刷新页面,查看newwork选项卡,选中XHR,可以看到异步加载(AJAX)和对应的Response中返回的json信息,证明可以从这里拿到数据。

9b38f77d04fc5aa98cfbe4d44e79da13.png

eb7aeeba011e85bead8d10f5fbe0bb5c.png

(4)通过翻页,可以找到表单数据,同时通过翻页,pn会不断变化,上述表单交互已经介绍,这里不再赘述。

b19aa2fca9ab0bf3c3033f6a3d9a0f19.png

(5)在netwoek->Preview中,可以看到每页信息数,同时信息总数。

83079ec63e7bdb32a51f47e2c017bb2b.png

(6)由于通过单一的cookie会被限制,所以补充了一个动态的cookie进行抓取数据,实验后可行,大家可以参考

def get_cookie():   # 原始网页的URL,即url_start   url = 'https://www.lagou.com/jobs/list_%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90?labelWords=&fromSearch=true&suginput='   s = requests.Session()   s.get(url, headers=headers, timeout=3)  # 请求首页获取cookies   cookie = s.cookies  # 为此次获取的cookies   return cookie

详细代码如下:

import requestsimport jsonimport timeimport pandas as pd#import csvheaders = {   'origin': 'https://www.lagou.com',   'accept': 'xxxx',   'user-agent': 'xxxx',   'referer': 'xxxx'}# 获取cookies值def get_cookie():   # 原始网页的URL,即url_start   url = 'https://www.lagou.com/jobs/list_%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90?labelWords=&fromSearch=true&suginput='   s = requests.Session()   s.get(url, headers=headers, timeout=3)  # 请求首页获取cookies   cookie = s.cookies  # 为此次获取的cookies   return cookie# 定义获取页数的函数def get_page(url, params):   html = requests.post(url, data=params, headers=headers, cookies=get_cookie(), timeout=5)   # 将网页的Html文件加载为json文件   json_data = json.loads(html.text)   # 解析json文件,后跟中括号为解析的路径   total_Count = json_data['content']['positionResult']['totalCount']   page_number = int(total_Count/15) if int(total_Count/15) < 30 else 30   # 调用get_info函数,传入url和页数   get_info(url, page_number)# 定义获取招聘信息函数def get_info(url, page):   for pn in range(1, page+1):       # post请求参数       params = {           "first": "true",           "pn": str(pn),           "kd": "大数据"       }       # 获取信息 并捕获异常       try:           html = requests.post(url, data=params, headers=headers, cookies=get_cookie(), timeout=5)           #print(url, html.status_code)           # 将网页的Html文件加载为json文件           json_data = json.loads(html.text)           # 解析json文件,后跟中括号为解析的路径           results = json_data['content']['positionResult']['result']           df = pd.DataFrame(results)           #print(df.iloc[:,0:6])           if pn == 1:               total_df = df           else:               total_df = pd.concat([total_df,df],axis=0)           # 睡眠2秒           time.sleep(2)       except requests.exceptions.ConnectionError:           print("requests.exceptions.ConnectionError")           pass       #total_df.to_csv('招聘信息.csv', sep = ',', header = True, index = False)       total_df.to_excel('大数据.xls',header=True, index=False)# 原始网页的URL#请求JSON数据的URLurl = "https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false"params = {   "first": "true",   "pn": 1,   "kd": "大数据"}get_page(url,params)

以上就是拉勾网数据抓取,一般最多只能抓取到不到500条数据,如果需要抓取更多还需深入研究。

--每天一小步、未来一大步!

ea4b39279fbc1790ca19b2154ad70b6e.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值