使用Selenium从中间事件捕获JSON数据

时间:2019-04-19 15:04:46

标签: python json selenium selenium-webdriver web-scraping

下面,我设置了一个脚本,该脚本仅在网站上执行搜索。目标是利用Selenium捕获从中间脚本触发的事件中捕获的JSON数据,即包括图像中所示的POST请求到“ https://www.botoxcosmetic.com/sc/api/findclinic/FindSpecialists”,而无需使用Selenium直接向该URL发送请求或请求库。最好的方法是什么(最好使用Python但可以使用任何语言)?

from selenium import webdriver
base_url = 'https://www.botoxcosmetic.com/women/find-a-botox-cosmetic-specialist'
driver = webdriver.Chrome()
driver.find_element_by_class_name('normalZip').send_keys('10022')
driver.find_element_by_class_name('normalSearch').click()

enter image description here

1 个答案:

答案 0 :(得分:1)

您将需要使用代理,我的建议是使用BrowserMob代理。

首先安装BrowserMob代理库:

pip install browsermob-proxy

然后,您需要下载latest release(在撰写本文时为2.1.4),将其解压缩,然后将其放置在项目目录中。这将是设置BrowserMob代理服务器时需要传递的位置(请参见下面的Server("browsermob-proxy-2.1.4/bin/browsermob-proxy")定义)

然后我将您的脚本更新为以下内容:

import json

from browsermobproxy import Server
from haralyzer import HarParser
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

base_url = 'https://www.botoxcosmetic.com'
server = Server("browsermob-proxy-2.1.4/bin/browsermob-proxy")
server.start()
proxy = server.create_proxy()

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy))

driver = webdriver.Chrome(options=chrome_options)
driver.get("{0}/women/find-a-botox-cosmetic-specialist".format(base_url))

proxy.new_har(options={"captureContent": "true"})
driver.find_element_by_class_name('normalZip').send_keys('10022')
driver.find_element_by_class_name('normalSearch').click()

WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#specialist-results > div")))

har_parser = HarParser(proxy.har)
for entry in har_parser.har_data["entries"]:
    if entry["request"]["url"] == "{0}/sc/api/findclinic/FindSpecialists".format(base_url):
        result = json.loads(entry["response"]["content"]["text"])

driver.quit()
server.stop()

这将启动BrowserMob代理实例,并捕获对FindSpecialists网络调用的响应,并将其作为JSON存储在结果变量中。

然后,您可以用它来做您想对响应做的任何事情。抱歉,如果代码没有您期望的那么干净,我不是本机Pythonista。

有用的参考是: