kaizty_playwerght.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import time
  4. import re
  5. import httpx
  6. from playwright.sync_api import sync_playwright
  7. url_photos = '/photos/'
  8. base_url = 'https://www.kaizty.com//photos/L2lBQ200aE0vOVNmUGcydzhhT296Zz09.html?page={}'
  9. headers = {
  10. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
  11. def clean_string(string):
  12. string = string.replace('Kaizty Photos: ', '')
  13. string = string.split('|')[0]
  14. string = re.sub(r'[^\u4e00-\u9fff a-zA-Z0-9]', '', string)
  15. string = string.replace(' ', '_')
  16. if string.endswith('_'):
  17. string = string[:-1]
  18. return string
  19. def each_page(page, photo_url, folder):
  20. img_suffix = photo_url.split('.')[-1]
  21. img_name = str(int(time.time())) + '.' + img_suffix
  22. img_content = page.goto(photo_url).body()
  23. with open(os.path.join(folder, img_name), 'wb') as f:
  24. f.write(img_content)
  25. time.sleep(2)
  26. def run(playwright):
  27. browser = playwright.webkit.launch(headless=True)
  28. context = browser.new_context()
  29. page = context.new_page()
  30. for page_num in range(1, 20):
  31. page.goto(base_url.format(page_num))
  32. title = page.title()
  33. # folder = clean_string(title)
  34. folder = 'aaa'
  35. if not os.path.exists(folder):
  36. print(f'new folder {folder}')
  37. os.makedirs(folder)
  38. page_source = page.content()
  39. photos_list = re.findall('<meta property="og:image" content="(.*?)"', page_source)
  40. for photo_url in photos_list:
  41. each_page(page, photo_url, folder)
  42. # 延时一下
  43. time.sleep(2)
  44. # 没找到下一页, 就退出循环
  45. if not page.query_selector('body > div.page-navigation > a.next'):
  46. print('no next page')
  47. break
  48. context.close()
  49. browser.close()
  50. with sync_playwright() as playwright:
  51. run(playwright)