python爬取国家法律法规数据库

打印 上一主题 下一主题

主题 1531|帖子 1531|积分 4593

1.页面

2.分析


发现导航栏有不同分类,f12查看网络接口,发现每个分类对应一个参数 

从列表进入内容,发现每条内容文件对应一个id,这个id是由列表页传过来的,从列表获取拼出内容的url,然后举行接口爬取内容的文件路径path,再下载文件,解析文件


3.准备工作

爬取的文件数据下载到文件夹中,其他数据存储到数据库中
4..完整代码

  1. import uuid
  2. import requests
  3. import sys
  4. import pymysql as mysql
  5. import datetime
  6. from docx import Document
  7. import time
  8. # 爬接口
  9. # 消除警告
  10. requests.packages.urllib3.disable_warnings()
  11. # 无法识别的乱码处理
  12. non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
  13. con = mysql.connect(host="127.0.0.1", port=3306, user="root", passwd="root", db="guojia_spider", charset="utf8")
  14. source = "国家法律法规数据库"
  15. cookies = {
  16.     'wzws_sessionid': 'gWU4ZGIxYYJmYWI4NWaAMTM5LjIxNC4zMi4yMjGgZtAiVw==',
  17.     'Hm_lvt_54434aa6770b6d9fef104d146430b53b': '1722493539,1724209491,1724916312',
  18.     'HMACCOUNT': '4FF444F068B3087E',
  19.     'Hm_lpvt_54434aa6770b6d9fef104d146430b53b': '1724979519',
  20. }
  21. headers = {
  22.     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  23.     'Connection': 'close'
  24. }
  25. # 列表请求参数
  26. params = {
  27.     'type': 'dfxfg',
  28.     'searchType': 'title;vague',
  29.     'sortTr': 'f_bbrq_s;desc',
  30.     'gbrqStart': '',
  31.     'gbrqEnd': '',
  32.     'sxrqStart': '',
  33.     'sxrqEnd': '',
  34.     'sort': 'true',
  35.     'page': '1',
  36.     'size': '10',
  37.     '_': '1724980047619',
  38. }
  39. # 内容请求参数
  40. data = {
  41.     'id': 'ZmY4MDgxODE4ZDczNmFjMTAxOGRjZmFlOTU2MTJlYWU%3D',
  42. }
  43. # 入库
  44. def inputdb(id, title, source_href, ddate, date2, content_label, content_nolabel, attachment, province):
  45.     global con, source
  46.     cursor1 = con.cursor()
  47.     public_time = ddate
  48.     create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  49.     # 标题相同 进行去重 避免数据重复
  50.     sql1 = "select * from 表名 where title ='%s'" % (title)
  51.     cursor1.execute(sql1)
  52.     results = cursor1.fetchall()
  53.     if len(results) > 0:
  54.         print('The data already exists---')
  55.         cursor1.close()
  56.         return
  57.     cursor1.close()
  58.     cursor2 = con.cursor()
  59.     if public_time is None or public_time == '':
  60.         public_time = ''
  61.     if date2 is None or date2 == '':
  62.         date2 = ''
  63.     if province != '' and public_time != '' and date2 != '':
  64.         sql2 = (
  65.                    "insert into 表名(id,title,source,source_href,public_time,expiry_time,content,content_text,create_time,province,attachment)"
  66.                    " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')") % (
  67.                    id, title, source, source_href, public_time, date2, content_label, content_nolabel, create_time, province, attachment)
  68.     elif province != '' and public_time != '' and date2 == '':
  69.         sql2 = (
  70.                    "insert into 表名(id,title,source,source_href,public_time,content,content_text,create_time,province,attachment)"
  71.                    " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')") % (
  72.                    id, title, source, source_href, public_time, content_label, content_nolabel, create_time, province, attachment)
  73.     elif province != '' and public_time == '' and date2 != '':
  74.         sql2 = (
  75.                    "insert into 表名(id,title,source,source_href,expiry_time,content,content_text,create_time,province,attachment)"
  76.                    " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')") % (
  77.                    id, title, source, source_href, date2, content_label, content_nolabel,create_time, province, attachment)
  78.     elif province == '' and public_time != '' and date2 != '':
  79.         sql2 = (
  80.                    "insert into 表名(id,title,source,source_href,public_time,expiry_time,content,content_text,create_time,attachment)"
  81.                    " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')") % (
  82.                    id, title, source, source_href, public_time, date2, content_label, content_nolabel,create_time, attachment)
  83.     elif province != '' and public_time == '' and date2 == '':
  84.         sql2 = (
  85.                    "insert into 表名(id,title,source,source_href,content,content_text,create_time,province,attachment)"
  86.                    " values('%s','%s','%s','%s','%s','%s','%s','%s','%s')") % (
  87.                    id, title, source, source_href, content_label, content_nolabel,create_time, province, attachment)
  88.     elif province == '' and public_time != '' and date2 == '':
  89.         sql2 = (
  90.                    "insert into 表名(id,title,source,source_href,expiry_time,content,content_text,create_time,attachment)"
  91.                    " values('%s','%s','%s','%s','%s','%s','%s','%s','%s')") % (
  92.                    id, title, source, source_href, public_time, content_label, content_nolabel,create_time, attachment)
  93.     elif province == '' and public_time == '' and date2 != '':
  94.         sql2 = (
  95.                    "insert into 表名(id,title,source,source_href,expiry_time,content,content_text,create_time,attachment)"
  96.                    " values('%s','%s','%s','%s','%s','%s','%s','%s','%s')") % (
  97.                    id, title, source, source_href, date2, content_label, content_nolabel,create_time, attachment)
  98.     else:
  99.         sql2 = (
  100.                    "insert into 表名(id,title,source,source_href,content,content_text,create_time,attachment)"
  101.                    " values('%s','%s','%s','%s','%s','%s','%s','%s')") % (
  102.                    id, title, source, source_href, content_label, content_nolabel,create_time, attachment)
  103.     cursor2.execute(sql2)
  104.     con.commit()
  105.     cursor2.close()
  106. # 雪花算法 获取id
  107. class Snowflake:
  108.     def __init__(self, machine_id):
  109.         self.machine_id = machine_id
  110.         self.sequence = 0
  111.         self.last_timestamp = -1
  112.     def generate_id(self):
  113.         timestamp = int(time.time() * 1000)
  114.         if timestamp < self.last_timestamp:
  115.             raise Exception("Clock moved backwards")
  116.         if timestamp == self.last_timestamp:
  117.             self.sequence = (self.sequence + 1) & 4095
  118.             if self.sequence == 0:
  119.                 timestamp = self.wait_next_millis(self.last_timestamp)
  120.         else:
  121.             self.sequence = 0
  122.         self.last_timestamp = timestamp
  123.         return ((timestamp - 1288834974657) << 22) | (self.machine_id << 12) | self.sequence
  124.     def wait_next_millis(self, last_timestamp):
  125.         timestamp = int(time.time() * 1000)
  126.         while timestamp <= last_timestamp:
  127.             timestamp = int(time.time() * 1000)
  128.         return timestamp
  129. if __name__ == '__main__':
  130.     # 地方性法规1-2229页
  131.     params['type'] = 'dfxfg'
  132.     # 司法解释
  133.     # params['type'] = 'sfjs'
  134.     # 法律
  135.     # params['type'] = 'fl'
  136.     # 行政法规
  137.     # params['type'] = 'xzfg'
  138.     # 根据参数不同 循环不同页码
  139.     for i in range(1, 2230):
  140.         num = 1
  141.         params['page'] = i
  142.         response = requests.get(
  143.             url='https://flk.npc.gov.cn/api/',
  144.             headers=headers,
  145.             params=params,
  146.             cookies=cookies,
  147.             verify=False
  148.         )
  149.         if response.status_code == 200:
  150.             response = response.json()
  151.             snowflake = Snowflake(1)
  152.             for j in response['result']['data']:
  153.                 print('---start running---')
  154.                 data['id'] = j['id']
  155.                 title = j['title']
  156.                 date = j['publish'] # 发布日期
  157.                 date2 = j['expiry'] # 生效日期
  158.                 if j['type'] == '地方性法规':
  159.                     province = str(j['office']).split('人')[0]
  160.                 else:
  161.                     province = ''
  162.                 uurl = 'https://flk.npc.gov.cn/api/detail'
  163.                 new_data = requests.post(url=uurl, data=data, headers=headers, cookies=cookies)
  164.                 # 避免网页504
  165.                 if new_data.status_code == 504:
  166.                     print("Error 504: Gateway Timeout")
  167.                 if new_data.status_code == 200:
  168.                     new_data = new_data.json()
  169.                     download_url = 'https://wb.flk.npc.gov.cn' + new_data['result']['body'][0]['path']
  170.                     text_p, text, attachment_url = "", "", ""
  171.                     if download_url.split('.')[-1].endswith('pdf'):
  172.                         download_url = 'https://wb.flk.npc.gov.cn' + new_data['result']['body'][1]['path']
  173.                     if download_url.split('.')[-1].endswith('docx'):
  174.                         name = str(uuid.uuid4().hex)
  175.                         attachment_url = '/spiderFiles/' + name + '.' + download_url.split('.')[-1]
  176.                         # 下载文件
  177.                         content = requests.get(url=download_url, headers=headers).content
  178.                         with open('D:\\spiderFiles\\' + name + '.' + download_url.split('.')[-1],
  179.                                   mode='wb') as f:
  180.                             f.write(content)
  181.                         # 解析文件
  182.                         doc = Document('D:\\spiderFiles\\' + name + '.' + download_url.split('.')[-1])
  183.                         for para in doc.paragraphs:
  184.                             text += para.text
  185.                             if para.text != None and para.text != "":
  186.                                 text_p += "<p>" + para.text + "</p>"
  187.                         # print(text_p)
  188.                     else:
  189.                         print('---check the file---')
  190.                     href = 'https://flk.npc.gov.cn/detail2.html?' + data['id']
  191.                     # id非自增 雪花算法随机生成
  192.                     id = snowflake.generate_id()
  193.                     inputdb(id, title, href, date, date2, text_p, text, attachment_url, province)
  194.                     time.sleep(1)
  195.                     print('The', i, 'page-the', num, 'data has been downloaded!!!')
  196.                     num += 1
  197.     print('The data has been downloaded and is up-to-date---')
  198.     con.close()
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

灌篮少年

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表