import httpx.py 821 B

123456789101112131415161718192021222324252627282930313233
  1. import httpx
  2. # 定义Splash服务器的URL
  3. SPLASH_URL = 'http://localhost:8050'
  4. # 定义Splash的API端点
  5. RENDER_HTML_ENDPOINT = SPLASH_URL + '/render.html'
  6. # 要访问的网页URL
  7. TARGET_URL = 'http://www.baidu.com'
  8. # 创建httpx客户端
  9. client = httpx.Client()
  10. # 发送POST请求到Splash,请求渲染TARGET_URL
  11. response = client.post(RENDER_HTML_ENDPOINT, data={'url': TARGET_URL})
  12. # 关闭客户端连接
  13. client.close()
  14. # 检查请求是否成功
  15. if response.status_code == 200:
  16. # 获取渲染后的HTML内容
  17. html_content = response.text
  18. print('HTML Content:')
  19. print(html_content)
  20. else:
  21. print('Failed to render the page:', response.status_code)
  22. exit(0)
  23. # 可选:保存渲染后的HTML到文件
  24. with open('baidu.html', 'w', encoding='utf-8') as file:
  25. file.write(html_content)