基于Python Selenium的使用和代理配置

基本使用

初始化driver

chrome

options = ChromeOptions()
# 忽略https警告
options.add_argument('--ignore-certificate-errors')
options.add_argument('--disable-gpu')
options.add_argument('--disable-cache')
# 无头模式
options.headless = True
# window.navigator.webdriver=true 修改
options.add_experimental_option('excludeSwitches', ['enable-automation'])
# 打开driver
self.driver = webdriver.Chrome(chrome_options=options)
# 设置超时时间的wait
self.wait = WebDriverWait(self.driver, 10)

firefox

profile = FirefoxProfile()
profile.set_preference('permissions.default.image', 2)  # 禁用加载图片
# 打开driver
self.driver = webdriver.Firefox(firefox_profile=profile)
# 设置超时时间
self.wait = WebDriverWait(self.driver, 10)

打开网页

# 清空cookies
self.driver.delete_all_cookies()
# 打开网页
self.driver.get(local_url)

选择标签

提供了多种方式的选择,可以根据标签id,class,class选择器,xpath 等等方式。如果没有找到则会报出异常信息。

# 单个
self.driver.find_element_by_class_name("user-tab")
# 多个
self.driver.find_elements_by_xpath("//div/div[2]/a")
# ...

也可以使用带有超时时间的wait来获取标签

self.wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='JDJRV-bigimg']/img")))

动作事件

点击

# 通过标签点击
element.click()
# 通过js点击
self.driver.execute_script("arguments[0].click();", element)

# 点击并按住某个标签(非必须)
ActionChains(self.driver).click_and_hold(element).perform()
# 抬起按键
ActionChains(self.driver).release().perform()

移动

# 移动到指定标签
ActionChains(self.driver).move_to_element(element).perform()
# 移动指定像素
ActionChains(self.driver).move_by_offset(xoffset=x, yoffset=y).perform()

输入

# 输入
input_ele.send_keys('123')
# 清空
input_ele.clear()

滚动

# js方式
self.driver.execute_script("window.scrollBy(0, 700)")
# 模拟方式 # headless时可能会失效,或者之前需要先点击一下
ActionChains(self.driver).send_keys(Keys.PAGE_DOWN).perform() 

抓取network

首先selenium的想要截获页面的network列表,需要依赖第三方组件 browsermobproxy。通过其提供的代理服务接口,将其设置到selenium 上,这样我们在操作页面的时候,就能抓取到页面的一些异步请求列表(http、https)。

初始化 browsermob-proxy

首先下载browsermob-proey relese包,由于该项目是java实现的。所以我们需要根据自己的平台去调用bin目录下对应的文件。

然后基本使用就是 browsermob-proxy 功能三部走。

def _init_proxy(self):
    """
    初始化代理服务
    """
    # 代理服务(这里是macOX的调用文件)
    path = r"/Users/xxx/browsermob-proxy-2.1.4/bin/browsermob-proxy"
    # 初始化一个代理Manager服务,并监听8180端口
    self.server = browsermobproxy.Server(path=path, options={'port': 8180})
    # 启动代理Manager服务
    self.server.start()
    # 向代理Manager服务申请一个代理服务
    self.proxy = self.server.create_proxy()
    
def _open_proxy(self, ref):
    """
    打开代理监控(要在网页打开前打开监控)
    :param ref:注册的名称
    :return:
    """
    options = {'captureContent': True, 'captureHeaders': True}
    self.proxy.new_har(ref, options=options)
    
def _get_network(self):
    """
    获取请求列表
    """
    # 取出请求列表
    result = self.proxy.har
    # 遍历请求列表信息
    for entry in result['log']['entries']:
        req_url = entry['request']['url']
        resp_content = entry["response"]['content']["text"]

chrome代理

options = ChromeOptions()
# options.add_argument('--proxy-server={0}'.format(self.proxy.proxy))
options.add_argument('--proxy-server={host}:{port}'.format(host="localhost", port=self.proxy.port))

# 其它配置...
self.driver = webdriver.Chrome(chrome_options=options)

firefox代理

profile = FirefoxProfile()

# http代理
profile.set_preference("network.proxy.type", 1)
# ip及其端口号配置为 http 协议代理
profile.set_preference("network.proxy.http", "localhost")
profile.set_preference("network.proxy.http_port", self.proxy.port)
# https代理
profile.set_preference('network.proxy.ssl', "localhost")
profile.set_preference('network.proxy.ssl_port', self.proxy.port)
# 所有协议共用一种 ip 及端口,如果单独配置,不必设置该项,因为其默认为 False
profile.set_preference("network.proxy.share_proxy_settings", True)

# 其它配置...
self.driver = webdriver.Firefox(firefox_profile=profile)

参考

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值