专栏名称: 51Testing软件测试网
51Testing软件测试网,人气最旺的软件测试技术门户,提供软件测试社区交流,软件测试博客,人才服务,测试沙龙,测试杂志,测试资料下载等全方位信息服务,是国内最专业的软件测试就业培训、企业服务供应商...
目录
相关文章推荐
51好读  ›  专栏  ›  51Testing软件测试网

人工智能测试之爬百度成语测成语接龙

51Testing软件测试网  · 公众号  · 测试  · 2019-10-17 17:28

正文

请到「今天看啥」查看全文


6 @license: Apache Licence
7 @file: get_idiom_from_baidu.py
8 @time: 2018/10/21 20:35
9 """
10
11 __author__ = 'albert'
12 __version__ = '1.0'
13
14 import json
15 import sqlite3
16
17 import os
18 import requests
19 import socket
20 import time
21 import sys
22
23 # 总页数,直接手动,不去获取了
24 page_count = 1546
25
26 # 组装请求头
27 header = {
28     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
29     'Accept-Encoding': 'gzip, deflate, sdch',
30     'Accept-Language': 'zh-CN,zh;q=0.9',
31     'Connection': 'keep-alive',
32     'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
33 }
34 # 默认数据库
35 db_filename = 'idiom.sqlite3'
36
37
38 def get_idiom_data(start_pagenum=1, end_pagenum=10, all=False):
39     '''
40       爬取百度成语数据,解析并保存到数据到数据库
41       :param start_pagenum: 默认从第1页开始
42       :param end_pagenum: 默认第10页结束
43       '''
44     global page_count, header
45
46     # 统计成语条数
47     idiom_count = 0
48     # 进度条
49     page_num = 0
50     get_url = 'https://hanyu.baidu.com/hanyu/ajax/search_list?wd=%E6%88%90%E8%AF%AD&from=poem&pn={}&_={}'.format(1, int(round(time.time() * 1000)))
51
52     # 获取全部成语
53     if all:
54         end_pagenum = page_count
55
56     for i in range(start_pagenum, end_pagenum + 1):
57         # 连接数据库
58         conn = sqlite3.connect(db_filename)
59         cursor = conn.cursor()
60
61         # 当前时间戳
62         # t = int(round(time.time() * 1000))
63         # 模拟请求获取json数据
64         try:
65             # 自动保存cookie
66             s = requests.session()
67             header['Referrer'] = get_url
68
69             # 百度 ajax 成语请求API
70             get_url = 'https://hanyu.baidu.com/hanyu/ajax/search_list?wd=%E6%88%90%E8%AF%AD&from=poem&pn={}&_={}'.format(i, int(round(time.time() * 1000)))
71
72             # 模拟请求
73             result = s.get(get_url, headers=header)
74             # 判断请求是否成功
75             if result.status_code == 200:
76                 res = json.loads(result.text)






请到「今天看啥」查看全文