一、背景

  1. URL地址:http://dgepb.dg.gov.cn/sjzxh.html
  2. 目标:批量下载图中的附件

image.png

二、实现过程

1.思路

  • 获取文件链接:通过网络抓包,可以很容易发现json数据格式

image.png

  • 构造出post参数即可

    1. post_params={
    2. 'page':'1', #页码,默认为1
    3. 'rows':'20', #每页多少条,最大20
    4. 'HBTB_XH':'','HBTB_XH_END':'','HBTB_XMMC':'','HBTB_JSDD':'','HBTB_JSDW':'','HBTB_SLRQ':'','HBTB_SLRQ_END':'',
    5. 'dirId':'402881204e959150014e959f42f30014', #文件夹编号
    6. 'subjectId':'93e889f2501d3fe8015024305bdf0efc',
    7. 'backPage':'','vcode':''
    8. }

    三、小结

  • 三页过后会有滑块验证码,目前显示不了,尚未解决

四、代码

  1. from os import error
  2. import requests
  3. import re
  4. import json
  5. from time import sleep
  6. from bs4 import BeautifulSoup
  7. from tqdm import tqdm
  8. #获取文件链接
  9. file_urls=[]
  10. file_names=[]
  11. count = int(input('请输入爬取页码数(1,2,3.....):'))
  12. headers = {
  13. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.81',
  14. 'Referer':'http://120.86.191.138/hbgs/zwgk/dirData.do?dirId=402881204e959150014e959f42f30014&subjectId=93e889f2501d3fe8015024305bdf0efc'
  15. }
  16. post_params={
  17. 'page':'1', #页码,默认为1
  18. 'rows':'20', #每页多少条,最大20
  19. 'HBTB_XH':'','HBTB_XH_END':'','HBTB_XMMC':'','HBTB_JSDD':'','HBTB_JSDW':'','HBTB_SLRQ':'','HBTB_SLRQ_END':'',
  20. 'dirId':'402881204e959150014e959f42f30014', #文件夹编号
  21. 'subjectId':'93e889f2501d3fe8015024305bdf0efc',
  22. 'backPage':'','vcode':''
  23. }
  24. path = 'http://120.86.191.138/hbgs/zwgk/item.do'
  25. print('开始爬取新闻链接...')
  26. for i in tqdm(range(1,count+1)):
  27. post_params['page']=i #第4页开始出现验证码验证,反爬虫
  28. req=requests.post(url=path,params=post_params,headers=headers)
  29. try:
  30. req.encoding='utf-8'
  31. file_json=req.json().get('rows')
  32. for item in file_json:
  33. file_url=item.get('HBTB_HPWJ')
  34. file_urls.append(file_url)
  35. file_name=file_url.split('/')[-1] #取文件名
  36. file_names.append(file_name)
  37. except :
  38. print('第{0}页出现error'.format(i))
  39. continue
  40. #print(file_urls,'\n')
  41. #print(file_names,'\n')
  42. #下载文件
  43. len=2 #下载文件数
  44. for i in range(1,len+1):
  45. req=requests.get(file_urls[i])
  46. with open (file_names[i],'wb') as f:
  47. f.write(req.content)
  48. print('---结束---')