大部分商业网站需要我们登录后才能爬取内容,所以对于爬虫来说,生成cookies给代理使用成为了一个必须要做的事情。今天我们交流下关于使用selenium访问目标网站遇到的一些问题。

因为业务需求我们需要采集小红书的一些数据,程序在挂上代理访问目标网站的时候弹出了验证框。如图所示

fccfb608-f39d-4671-8ceb-0340549e140d.png

这个问题从来没有遇到过,我以为是的代理的问题,咨询客服才知道这个是因为我的浏览器的驱动和版本的问题,然后更新了新版本就可以解决了。那我们分享下使用chrome driver来进行登录和cookie的生成。

  1. import os
  2. import time
  3. import zipfile
  4. from selenium import webdriver
  5. from selenium.common.exceptions import TimeoutException
  6. from selenium.webdriver.common.by import By
  7. from selenium.webdriver.support import expected_conditions as EC
  8. from selenium.webdriver.support.ui import WebDriverWait
  9. class GenCookies(object):
  10. USER_AGENT = open(\'useragents.txt\').readlines()
  11. # 16yun 代理配置
  12. PROXY_HOST = \'t.16yun.cn\' # proxy or host
  13. PROXY_PORT = 31111 # port
  14. PROXY_USER = \'USERNAME\' # username
  15. PROXY_PASS = \'PASSWORD\' # password
  16. @classmethod
  17. def get_chromedriver(cls, use_proxy=False, user_agent=None):
  18. manifest_json = """
  19. {
  20. "version": "1.0.0",
  21. "manifest_version": 2,
  22. "name": "Chrome Proxy",
  23. "permissions": [
  24. "proxy",
  25. "tabs",
  26. "unlimitedStorage",
  27. "storage",
  28. "<all_urls>",
  29. "webRequest",
  30. "webRequestBlocking"
  31. ],
  32. "background": {
  33. "scripts": ["background.js"]
  34. },
  35. "minimum_chrome_version":"22.0.0"
  36. }
  37. """
  38. background_js = """
  39. var config = {
  40. mode: "fixed_servers",
  41. rules: {
  42. singleProxy: {
  43. scheme: "http",
  44. host: "%s",
  45. port: parseInt(%s)
  46. },
  47. bypassList: ["localhost"]
  48. }
  49. };
  50. chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
  51. function callbackFn(details) {
  52. return {
  53. authCredentials: {
  54. username: "%s",
  55. password: "%s"
  56. }
  57. };
  58. }
  59. chrome.webRequest.onAuthRequired.addListener(
  60. callbackFn,
  61. {urls: ["<all_urls>"]},
  62. [\'blocking\']
  63. );
  64. """ % (cls.PROXY_HOST, cls.PROXY_PORT, cls.PROXY_USER, cls.PROXY_PASS)
  65. path = os.path.dirname(os.path.abspath(__file__))
  66. chrome_options = webdriver.ChromeOptions()
  67. if use_proxy:
  68. pluginfile = \'proxy_auth_plugin.zip\'
  69. with zipfile.ZipFile(pluginfile, \'w\') as zp:
  70. zp.writestr("manifest.json", manifest_json)
  71. zp.writestr("background.js", background_js)
  72. chrome_options.add_extension(pluginfile)
  73. if user_agent:
版权声明:本文为mmz77-aa原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/mmz77-aa/p/14681939.html