美文网首页
Selenium+Browsermob-Proxy获取浏览器Ne

Selenium+Browsermob-Proxy获取浏览器Ne

作者: 山猪打不过家猪 | 来源:发表于2021-05-25 11:10 被阅读0次

写在前面

尝试使用Selenium和Browsermob-Proxy把network里面的数据扒下来。个人觉得这样扒数据又全又清晰,遂写下本文记录扒拉勾网数据时的踩坑过程。还用于个人回顾或给正在坑里的朋友提供一丢丢一丢丢的帮助。
Selenium

安装驱动,建议把驱动放在python.exe同级目录下,使用时可以不用写驱动地址
驱动要与自己的chrome浏览器版本相适应
Chrome Selenium驱动下载
Browsermob-Proxy下载

image.png
# 暂停程序运行
import time
# 后面扒下来的数据是字符串里面包着字典,毫无可读性,可以通过json字符串和python字典的相互转换来提高可读性
import json
from browsermobproxy import Server
from selenium import webdriver
# 配置代理用
from selenium.webdriver.chrome.options import Option

开启代理

BMPserver = Server(r'D:\Apython\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat')
BMPserver.start()
BMPproxy = BMPserver.create_proxy()

全部代码

import time
import json
from browsermobproxy import Server
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


def main():
    # 开启代理
    BMPserver = Server(r'D:\Apython\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat')
    BMPserver.start()
    BMPproxy = BMPserver.create_proxy()

    # 配置代理启动webdriver
    chrome_options = Options()
    chrome_options.add_argument('--ignore-certificate-errors')
    chrome_options.add_argument('--proxy-server={}'.format(BMPproxy.proxy))
    brosver = webdriver.Chrome(executable_path="D:\Apython\chromedriver.exe",options=chrome_options)

    # 获取返回内容
    url = "https://m.lagou.com/search.html"
    BMPproxy.new_har("lagou",options={'captureContent': True,'captureContent': True})

    # 模拟浏览器
    brosver.get(url)
    # 搜索classname为inputer的Element对象
    searchBox = brosver.find_element_by_class_name("inputer")
    # 查找搜索按钮
    button = brosver.find_element_by_class_name("search")
    # 向搜索文本框送入关键字
    searchBox.send_keys("数据分析")
    # 点击搜索按钮
    button.click()
    time.sleep(3)

    result = BMPproxy.har
    # result_json = json.dumps(result,indent=4)
    # with open("lagoujob.json","w",errors="igone") as f:
    #     f.write(result_json)
    for entry in result['log']['entries']:
        entry_url = entry['request']['url']
        # 根据URL找到数据接口
        if "city=%E5%85%A8%E5%9B%BD&positionName=%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90" in entry_url:
            # 获取接口返回内容
            _response = entry['response']
            _content = _response['content']['text']
            # 返回的均是字符串包着字典,为了提高可读性,先将数据转换成python字典,再转成json数据
            content_dict = json.loads(_content)
            content_json = json.dumps(content_dict,indent=4)
        else:
            continue
    print(content_json)

main()

原文链接

相关文章

网友评论

      本文标题:Selenium+Browsermob-Proxy获取浏览器Ne

      本文链接:https://www.haomeiwen.com/subject/mqdxsltx.html