python中地图测距

百度地图测距-终稿V3.0:

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import xlwt
import xlwings as xw
from selenium import webdriver
import time
from selenium.webdriver import Chrome, ChromeOptions
import pandas as pd
import json


def data_a(start, end):
    df = pd.DataFrame()
    distance = []
    # 清空数据
    try:
        driver.find_element_by_xpath(
            '//html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/input').clear()
        driver.find_element_by_xpath(
            '//html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[2]/input').clear()
        driver.find_element_by_xpath("//div['routebox-input route-start']/input[@class='route-start-input']").send_keys(
            start)#起点
        driver.find_element_by_xpath(
            "//div[@class='routebox-input route-end']/input[@class='route-end-input']").send_keys(
            end)#终点
        time.sleep(2)
        driver.find_element_by_id('search-button').click()  # 模拟点击
        time.sleep(3)
        driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_0_0']").click()  # 点击起点
        time.sleep(2)
        driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_1_0']").click()  # 点击终点起点
        # driver.find_element_by_xpath("//tbody/tr/td[2]/div[@class='selBtn']").click()#点击起点
        # driver.find_element_by_xpath("//tbody/tr/td[2]/div[@class='selBtn']").click()  # 点击起点
        html = BeautifulSoup(driver.page_source, 'html.parser')
        source = driver.page_source
        html = BeautifulSoup(source, "html.parser")
    except:
        print("点击错误1")
        # driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_1_0']").click()  # 点击终点起点
        try:
            time.sleep(4)
            driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_1_0']").click()  # 点击终点起点
            time.sleep(3)
            print("执行")
        except:
            print("点击错误2")
            html = BeautifulSoup(driver.page_source, 'html.parser')
            # time.sleep(1.5)
            source = driver.page_source
            html = BeautifulSoup(source, "html.parser")
        # print("点击错误3")
        html = BeautifulSoup(driver.page_source, 'html.parser')
        # time.sleep(1.5)
        source = driver.page_source
        html = BeautifulSoup(source, "html.parser")

    with open('rr.html', 'w', encoding='utf-8') as f:  # 写入网页
        f.write(source)
    # time.sleep(1)
    # with open('rr.html', 'r', encoding='utf-8') as f:#打开网页
    #     html_a = BeautifulSoup(f, 'lxml')
    # 获取距离
    html.list = html.find_all('div', attrs={'class': 'navtrans-navlist-title'})
    for i, item in enumerate(html.list):
        try:
            distance.append(item.find_all('span')[2].text.strip('公里'))
            # print(item.find_all('span')[2].text.strip('公里'),)
            df["start"] = start,
            df["end"] = end,
            df["距离"] = (distance[0]),
            # df.to_json('distance.json', orient='records', indent=1, force_ascii=False)  # ,orient="values")
            # print(df)
        except:
            print(str(i), "网页获取错误")
    return df


df = pd.DataFrame()
if __name__ == "__main__":

    opt = ChromeOptions()  # 创建Chrome参数对象
    opt.headless = False  # 把Chrome设置成可视化无界面模式,windows/Linux 皆可
    driver = Chrome(options=opt)
    # driver = webdriver.Chrome()
    url="https://map.baidu.com/?newmap=1&shareurl=1&l=12&tn=B_NORMAL_MAP&hb=B_SATELLITE_STREET&c=13376484,3517857"#"https://map.baidu.com/@13376484,3517857,12z"
    driver.get(url)#'https://map.baidu.com/'
    driver.find_element_by_xpath(
        "//div[@class='searchbox-content-button right-button route-button loading-button']").click()  # 点击路线导航
    driver.find_element_by_xpath(
        "//div[@class='searchbox-content-common route-tabs']/div[@class='tab-item drive-tab']/span").click()  # 点击驾车导航
    location = ['北京', '上海', '深圳', '合肥', '杭州']
    app = xw.App(visible=False, add_book=False)
    wb = app.books.open('distance.xlsx')
    # 创建一个worksheet
    sh = wb.sheets['distance']
    rng_start = [i for i in sh.range("B:B").value if i != None]  # 单元格内容
    rng_end = [i for i in sh.range("C:C").value if i != None]  # 单元格内容
    j = sh.range('a1').expand('table').rows.count  # 序号
    for i in range(len(rng_start) - 1):
        try:
            # for i in range(len(location)):

            # df_a = data_a(location[i], location[i + 1])  # 执行查询
            df_a = data_a(rng_start[i + 1], rng_end[i + 1])  # 执行查询
            df = pd.concat([df_a, df], axis=0)  # 加入基础数据列
            df.to_json('distance.json', orient='records', indent=1, force_ascii=False)  # ,orient="values")
            df.to_csv("distance.csv", mode="a+", header=None, index=None, encoding="utf-8-sig", sep=',')
        except:
            print('查询错误')

    # 距离写入Jason
    # df.to_json('distance.json', orient='records', indent=1, force_ascii=False)  # ,orient="values")
    # 读取json
    with open("distance.json", 'r', encoding='utf-8') as f:
        data = json.load(f)
    print(data)

    app.display_alerts = False
    app.screen_updating = False

    for i in range(len(data)):  # 写入数据
        try:
            sh.cells[i + 1, 0].value = i + 1
            sh.cells[i + 1, 1].value = data[i]["start"]
            sh.cells[i + 1, 2].value = data[i]["end"]
            sh.cells[i + 1, 3].value = data[i]["距离"]
        except:
            print('写入错误')
    try:
        wb.save('distance.xlsx')
        wb.close()
        app.quit()
        # 获得当前窗口句柄
        sreach_windows = driver.current_window_handle
        driver.quit()
        # 获得当前所有打开的窗口的句柄
        all_handles = driver.window_handles
        for handle in all_handles:
            driver.switch_to.window(handle)
            driver.close()
    except:
        print('保存异常')

# print(html)
# html.list = html.find_all('div', attrs={'class': 'sckrox'})
# print(html.list)


# str=['中国铝业','中国核电','中国']
# print(str[1])

# driver.find_element_by_id().send_keys()
# driver.find_element_by_name()
# driver.find_elements_by_class_name()
# https://map.baidu.com/dir/%E4%B8%8A%E6%B5%B7%E5%B8%82/%E6%9D%AD%E5%B7%9E%E5%B8%82/@13409603.494459692,3577628.985,10.23z?querytype=nav&c=29&sn=0$$8eb697c2bdf8bae8b6f42fe7$$13523308,3641053$$%E4%B8%8A%E6%B5%B7%E5%B8%82$$0$$$$&en=0$$99f429f6963d1f271fe999e7$$13382445,3514415$$%E6%9D%AD%E5%B7%9E%E5%B8%82$$0$$$$&sc=29&ec=29&pn=0&rn=5&mrs=1&version=4&route_traffic=1&sy=0&da_src=shareurl')
# driver.find_element_by_xpath(
#     "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='sole-searchbox-content']/div[@class='searchbox-content-button right-button route-button loading-button']").click()
# driver.find_element_by_xpath(
#     "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='route-searchbox-content']/div[@class='route-header']/div[@class='searchbox-content-common route-tabs']/div[@class='tab-item walk-tab']/span").click()

百度地图测距:

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import xlwt
import xlwings as xw
from selenium import webdriver
import time
from selenium.webdriver import Chrome, ChromeOptions
import pandas as pd
import json


def data_a(start, end):
    df = pd.DataFrame()
    distance = []
    # 清空数据
    driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/input').clear()
    driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[2]/input').clear()
    driver.find_element_by_xpath("//div['routebox-input route-start']/input[@class='route-start-input']").send_keys(
        start)
    driver.find_element_by_xpath("//div[@class='routebox-input route-end']/input[@class='route-end-input']").send_keys(
        end)
    driver.find_element_by_id('search-button').click()  # 模拟点击
    html = BeautifulSoup(driver.page_source, 'html.parser')
    time.sleep(3)
    source = driver.page_source
    html = BeautifulSoup(source, "html.parser")
    with open('rr.html', 'w', encoding='utf-8') as f:  # 写入网页
        f.write(source)
    # time.sleep(3)
    # with open('rr.html', 'r', encoding='utf-8') as f:#打开网页
    #     html_a = BeautifulSoup(f, 'lxml')
    # 获取距离
    html.list = html.find_all('div', attrs={'class': 'navtrans-navlist-title'})
    for i, item in enumerate(html.list):
        try:
            distance.append(item.find_all('span')[2].text.strip('公里'))
            # print(item.find_all('span')[2].text.strip('公里'),)
            df["start"] = start,
            df["end"] = end,
            df["距离"] = (distance[0]),
            # print(df)
        except:
            print(str(i), "网页获取错误")
    return df


df = pd.DataFrame()
if __name__ == "__main__":

    opt = ChromeOptions()  # 创建Chrome参数对象
    opt.headless = False  # 把Chrome设置成可视化无界面模式,windows/Linux 皆可
    driver = Chrome(options=opt)
    # driver = webdriver.Chrome()
    driver.get('https://map.baidu.com/')
    driver.find_element_by_xpath(
        "//div[@class='searchbox-content-button right-button route-button loading-button']").click()  # 点击路线导航
    driver.find_element_by_xpath(
        "//div[@class='searchbox-content-common route-tabs']/div[@class='tab-item drive-tab']/span").click()  # 点击驾车导航
    location = ['北京', '上海', '深圳', '合肥', '杭州']
    app = xw.App(visible=True, add_book=False)
    wb = app.books.open('distance.xlsx')
    # 创建一个worksheet
    sh = wb.sheets['distance']
    rng_start = [i for i in sh.range("B:B").value if i != None]  # 单元格内容
    rng_end = [i for i in sh.range("C:C").value if i != None]  # 单元格内容
    j = sh.range('a1').expand('table').rows.count  # 序号
    for i in range(len(rng_start) - 1):
        try:
            # for i in range(len(location)):

            # df_a = data_a(location[i], location[i + 1])  # 执行查询
            df_a = data_a(rng_start[i + 1], rng_end[i + 1])  # 执行查询
            df = pd.concat([df_a, df], axis=0)  # 加入基础数据列
        except:
            print('查询错误')

    # 距离写入Jason
    df.to_json('distance.json', orient='records', indent=1, force_ascii=False)  # ,orient="values")
    # 读取json
    with open("distance.json", 'r', encoding='utf-8') as f:
        data = json.load(f)
    print(data)

    app.display_alerts = False
    app.screen_updating = False

    for i in range(len(data)):  # 写入数据
        try:
            sh.cells[i + 1, 0].value = i + 1
            sh.cells[i + 1, 1].value = data[i]["start"]
            sh.cells[i + 1, 2].value = data[i]["end"]
            sh.cells[i + 1, 3].value = data[i]["距离"]
        except:
            print('写入错误')
    try:
        wb.save('distance.xlsx')
        wb.close()
        app.quit()
        # 获得当前窗口句柄
        sreach_windows = driver.current_window_handle
        driver.quit()
        # 获得当前所有打开的窗口的句柄
        all_handles = driver.window_handles
        for handle in all_handles:
            driver.switch_to.window(handle)
            driver.close()
    except:
        print('保存异常')

# print(html)
# html.list = html.find_all('div', attrs={'class': 'sckrox'})
# print(html.list)


# str=['中国铝业','中国核电','中国']
# print(str[1])

# driver.find_element_by_id().send_keys()
# driver.find_element_by_name()
# driver.find_elements_by_class_name()
# https://map.baidu.com/dir/%E4%B8%8A%E6%B5%B7%E5%B8%82/%E6%9D%AD%E5%B7%9E%E5%B8%82/@13409603.494459692,3577628.985,10.23z?querytype=nav&c=29&sn=0$$8eb697c2bdf8bae8b6f42fe7$$13523308,3641053$$%E4%B8%8A%E6%B5%B7%E5%B8%82$$0$$$$&en=0$$99f429f6963d1f271fe999e7$$13382445,3514415$$%E6%9D%AD%E5%B7%9E%E5%B8%82$$0$$$$&sc=29&ec=29&pn=0&rn=5&mrs=1&version=4&route_traffic=1&sy=0&da_src=shareurl')
# driver.find_element_by_xpath(
#     "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='sole-searchbox-content']/div[@class='searchbox-content-button right-button route-button loading-button']").click()
# driver.find_element_by_xpath(
#     "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='route-searchbox-content']/div[@class='route-header']/div[@class='searchbox-content-common route-tabs']/div[@class='tab-item walk-tab']/span").click()

python中支持库发模式,即点击起点和自动城市模式:

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import xlwt
import xlwings as xw
from selenium import webdriver
import time
from selenium.webdriver import Chrome, ChromeOptions
import pandas as pd
import json


def data_a(start, end):
    df = pd.DataFrame()
    distance = []
    # 清空数据
    try:
        driver.find_element_by_xpath('//html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/input').clear()
        driver.find_element_by_xpath('//html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[2]/input').clear()
        driver.find_element_by_xpath("//div['routebox-input route-start']/input[@class='route-start-input']").send_keys(
            start)
        driver.find_element_by_xpath("//div[@class='routebox-input route-end']/input[@class='route-end-input']").send_keys(
            end)
        time.sleep(1.5)
        driver.find_element_by_id('search-button').click()  # 模拟点击
        time.sleep(2)
        driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_0_0']").click()  # 点击起点
        time.sleep(2)
        driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_1_0']").click()  # 点击起点
        # driver.find_element_by_xpath("//tbody/tr/td[2]/div[@class='selBtn']").click()#点击起点
        # driver.find_element_by_xpath("//tbody/tr/td[2]/div[@class='selBtn']").click()  # 点击起点
        html = BeautifulSoup(driver.page_source, 'html.parser')
        time.sleep(1.5)
        source = driver.page_source
        html = BeautifulSoup(source, "html.parser")
    except:
        print("点击错误")
        html = BeautifulSoup(driver.page_source, 'html.parser')
        time.sleep(1.5)
        source = driver.page_source
        html = BeautifulSoup(source, "html.parser")


    with open('rr.html', 'w', encoding='utf-8') as f:  # 写入网页
        f.write(source)
    # time.sleep(1)
    # with open('rr.html', 'r', encoding='utf-8') as f:#打开网页
    #     html_a = BeautifulSoup(f, 'lxml')
    # 获取距离
    html.list = html.find_all('div', attrs={'class': 'navtrans-navlist-title'})
    for i, item in enumerate(html.list):
        try:
            distance.append(item.find_all('span')[2].text.strip('公里'))
            # print(item.find_all('span')[2].text.strip('公里'),)
            df["start"] = start,
            df["end"] = end,
            df["距离"] = (distance[0]),
            # print(df)
        except:
            print(str(i), "网页获取错误")
    return df


df = pd.DataFrame()
if __name__ == "__main__":

    opt = ChromeOptions()  # 创建Chrome参数对象
    opt.headless = False  # 把Chrome设置成可视化无界面模式,windows/Linux 皆可
    driver = Chrome(options=opt)
    # driver = webdriver.Chrome()
    driver.get('https://map.baidu.com/')
    driver.find_element_by_xpath(
        "//div[@class='searchbox-content-button right-button route-button loading-button']").click()  # 点击路线导航
    driver.find_element_by_xpath(
        "//div[@class='searchbox-content-common route-tabs']/div[@class='tab-item drive-tab']/span").click()  # 点击驾车导航
    location = ['北京', '上海', '深圳', '合肥', '杭州']
    app = xw.App(visible=False, add_book=False)
    wb = app.books.open('distance.xlsx')
    # 创建一个worksheet
    sh = wb.sheets['distance']
    rng_start = [i for i in sh.range("B:B").value if i != None]  # 单元格内容
    rng_end = [i for i in sh.range("C:C").value if i != None]  # 单元格内容
    j = sh.range('a1').expand('table').rows.count  # 序号
    for i in range(len(rng_start) - 1):
        try:
            # for i in range(len(location)):

            # df_a = data_a(location[i], location[i + 1])  # 执行查询
            df_a = data_a(rng_start[i + 1], rng_end[i + 1])  # 执行查询
            df = pd.concat([df_a, df], axis=0)  # 加入基础数据列
        except:
            print('查询错误')

    # 距离写入Jason
    df.to_json('distance.json', orient='records', indent=1, force_ascii=False)  # ,orient="values")
    # 读取json
    with open("distance.json", 'r', encoding='utf-8') as f:
        data = json.load(f)
    print(data)

    app.display_alerts = False
    app.screen_updating = False

    for i in range(len(data)):  # 写入数据
        try:
            sh.cells[i + 1, 0].value = i + 1
            sh.cells[i + 1, 1].value = data[i]["start"]
            sh.cells[i + 1, 2].value = data[i]["end"]
            sh.cells[i + 1, 3].value = data[i]["距离"]
        except:
            print('写入错误')
    try:
        wb.save('distance.xlsx')
        wb.close()
        app.quit()
        # 获得当前窗口句柄
        sreach_windows = driver.current_window_handle
        driver.quit()
        # 获得当前所有打开的窗口的句柄
        all_handles = driver.window_handles
        for handle in all_handles:
            driver.switch_to.window(handle)
            driver.close()
    except:
        print('保存异常')

# print(html)
# html.list = html.find_all('div', attrs={'class': 'sckrox'})
# print(html.list)


# str=['中国铝业','中国核电','中国']
# print(str[1])

# driver.find_element_by_id().send_keys()
# driver.find_element_by_name()
# driver.find_elements_by_class_name()
# https://map.baidu.com/dir/%E4%B8%8A%E6%B5%B7%E5%B8%82/%E6%9D%AD%E5%B7%9E%E5%B8%82/@13409603.494459692,3577628.985,10.23z?querytype=nav&c=29&sn=0$$8eb697c2bdf8bae8b6f42fe7$$13523308,3641053$$%E4%B8%8A%E6%B5%B7%E5%B8%82$$0$$$$&en=0$$99f429f6963d1f271fe999e7$$13382445,3514415$$%E6%9D%AD%E5%B7%9E%E5%B8%82$$0$$$$&sc=29&ec=29&pn=0&rn=5&mrs=1&version=4&route_traffic=1&sy=0&da_src=shareurl')
# driver.find_element_by_xpath(
#     "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='sole-searchbox-content']/div[@class='searchbox-content-button right-button route-button loading-button']").click()
# driver.find_element_by_xpath(
#     "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='route-searchbox-content']/div[@class='route-header']/div[@class='searchbox-content-common route-tabs']/div[@class='tab-item walk-tab']/span").click()

python中支持点击单独目的地终点:

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json
import xlwt
import xlwings as xw
from selenium import webdriver
import time
from selenium.webdriver import Chrome, ChromeOptions
import pandas as pd
import json


def data_a(start, end):
    df = pd.DataFrame()
    distance = []
    # 清空数据
    try:
        driver.find_element_by_xpath('//html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/input').clear()
        driver.find_element_by_xpath('//html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[2]/input').clear()
        driver.find_element_by_xpath("//div['routebox-input route-start']/input[@class='route-start-input']").send_keys(
            start)
        driver.find_element_by_xpath("//div[@class='routebox-input route-end']/input[@class='route-end-input']").send_keys(
            end)
        time.sleep(1.5)
        driver.find_element_by_id('search-button').click()  # 模拟点击
        time.sleep(2)
        driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_0_0']").click()  # 点击起点
        time.sleep(2)
        driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_1_0']").click()  # 点击起点
        # driver.find_element_by_xpath("//tbody/tr/td[2]/div[@class='selBtn']").click()#点击起点
        # driver.find_element_by_xpath("//tbody/tr/td[2]/div[@class='selBtn']").click()  # 点击起点
        html = BeautifulSoup(driver.page_source, 'html.parser')
        time.sleep(2)
        source = driver.page_source
        html = BeautifulSoup(source, "html.parser")
    except:
        try:
            time.sleep(2)
            driver.find_element_by_xpath("//tbody/tr/td[2]/div[@tid='selBtn_1_0']").click()  # 点击起点
        except:
            print("点击错误")
            html = BeautifulSoup(driver.page_source, 'html.parser')
            # time.sleep(1.5)
            source = driver.page_source
            html = BeautifulSoup(source, "html.parser")
        print("点击错误")
        html = BeautifulSoup(driver.page_source, 'html.parser')
        # time.sleep(1.5)
        source = driver.page_source
        html = BeautifulSoup(source, "html.parser")

    with open('rr.html', 'w', encoding='utf-8') as f:  # 写入网页
        f.write(source)
    # time.sleep(1)
    # with open('rr.html', 'r', encoding='utf-8') as f:#打开网页
    #     html_a = BeautifulSoup(f, 'lxml')
    # 获取距离
    html.list = html.find_all('div', attrs={'class': 'navtrans-navlist-title'})
    for i, item in enumerate(html.list):
        try:
            distance.append(item.find_all('span')[2].text.strip('公里'))
            # print(item.find_all('span')[2].text.strip('公里'),)
            df["start"] = start,
            df["end"] = end,
            df["距离"] = (distance[0]),
            # print(df)
        except:
            print(str(i), "网页获取错误")
    return df


df = pd.DataFrame()
if __name__ == "__main__":

    opt = ChromeOptions()  # 创建Chrome参数对象
    opt.headless = False  # 把Chrome设置成可视化无界面模式,windows/Linux 皆可
    driver = Chrome(options=opt)
    # driver = webdriver.Chrome()
    driver.get('https://map.baidu.com/')
    driver.find_element_by_xpath(
        "//div[@class='searchbox-content-button right-button route-button loading-button']").click()  # 点击路线导航
    driver.find_element_by_xpath(
        "//div[@class='searchbox-content-common route-tabs']/div[@class='tab-item drive-tab']/span").click()  # 点击驾车导航
    location = ['北京', '上海', '深圳', '合肥', '杭州']
    app = xw.App(visible=False, add_book=False)
    wb = app.books.open('distance.xlsx')
    # 创建一个worksheet
    sh = wb.sheets['distance']
    rng_start = [i for i in sh.range("B:B").value if i != None]  # 单元格内容
    rng_end = [i for i in sh.range("C:C").value if i != None]  # 单元格内容
    j = sh.range('a1').expand('table').rows.count  # 序号
    for i in range(len(rng_start) - 1):
        try:
            # for i in range(len(location)):

            # df_a = data_a(location[i], location[i + 1])  # 执行查询
            df_a = data_a(rng_start[i + 1], rng_end[i + 1])  # 执行查询
            df = pd.concat([df_a, df], axis=0)  # 加入基础数据列
        except:
            print('查询错误')

    # 距离写入Jason
    df.to_json('distance.json', orient='records', indent=1, force_ascii=False)  # ,orient="values")
    # 读取json
    with open("distance.json", 'r', encoding='utf-8') as f:
        data = json.load(f)
    print(data)

    app.display_alerts = False
    app.screen_updating = False

    for i in range(len(data)):  # 写入数据
        try:
            sh.cells[i + 1, 0].value = i + 1
            sh.cells[i + 1, 1].value = data[i]["start"]
            sh.cells[i + 1, 2].value = data[i]["end"]
            sh.cells[i + 1, 3].value = data[i]["距离"]
        except:
            print('写入错误')
    try:
        wb.save('distance.xlsx')
        wb.close()
        app.quit()
        # 获得当前窗口句柄
        sreach_windows = driver.current_window_handle
        driver.quit()
        # 获得当前所有打开的窗口的句柄
        all_handles = driver.window_handles
        for handle in all_handles:
            driver.switch_to.window(handle)
            driver.close()
    except:
        print('保存异常')

# print(html)
# html.list = html.find_all('div', attrs={'class': 'sckrox'})
# print(html.list)


# str=['中国铝业','中国核电','中国']
# print(str[1])

# driver.find_element_by_id().send_keys()
# driver.find_element_by_name()
# driver.find_elements_by_class_name()
# https://map.baidu.com/dir/%E4%B8%8A%E6%B5%B7%E5%B8%82/%E6%9D%AD%E5%B7%9E%E5%B8%82/@13409603.494459692,3577628.985,10.23z?querytype=nav&c=29&sn=0$$8eb697c2bdf8bae8b6f42fe7$$13523308,3641053$$%E4%B8%8A%E6%B5%B7%E5%B8%82$$0$$$$&en=0$$99f429f6963d1f271fe999e7$$13382445,3514415$$%E6%9D%AD%E5%B7%9E%E5%B8%82$$0$$$$&sc=29&ec=29&pn=0&rn=5&mrs=1&version=4&route_traffic=1&sy=0&da_src=shareurl')
# driver.find_element_by_xpath(
#     "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='sole-searchbox-content']/div[@class='searchbox-content-button right-button route-button loading-button']").click()
# driver.find_element_by_xpath(
#     "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='route-searchbox-content']/div[@class='route-header']/div[@class='searchbox-content-common route-tabs']/div[@class='tab-item walk-tab']/span").click()

python百度地图测距测试:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import re

# vertion 1.0
driver = webdriver.Chrome()
driver.get('https://map.baidu.com/')

driver.find_element_by_xpath(
    "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='sole-searchbox-content']/div[@class='searchbox-content-button right-button route-button loading-button']").click()
driver.find_element_by_xpath(
    "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='route-searchbox-content']/div[@class='route-header']/div[@class='searchbox-content-common route-tabs']/div[@class='tab-item walk-tab']/span").click()


# 单击第一个按钮进入搜索界面

def startSpide(start, end):
    # start是第一输入框的内容,end是第二个,startSpide爬两地点间时间文字信息
    driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/input').clear()
    driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div[2]/div[2]/div/div[2]/div[2]/input').clear()
    # 清空两个输入框,即问号按键

    driver.find_element_by_xpath(
        "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='route-searchbox-content']/div[@class='routebox']/div[@class='searchbox-content-common routebox-content']/div[@class='routebox-inputs']/div[@class='routebox-input route-start']/input[@class='route-start-input']").send_keys(
        start)
    driver.find_element_by_xpath(
        "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/div[@id='searchbox-container']/div[@id='route-searchbox-content']/div[@class='routebox']/div[@class='searchbox-content-common routebox-content']/div[@class='routebox-inputs']/div[@class='routebox-input route-end']/input[@class='route-end-input']").send_keys(
        end)
    # 在两个框内输入字符start和end

    driver.find_element_by_xpath(
        "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/button[@id='search-button']").click()
    # 点击搜索

    time.sleep(2)
    try:
        driver.find_element_by_xpath(
            "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/ul[@id='cards-level1']/li[1]/div[@class='RouteAddressOuterBkg']/div[@class='RouteAddressInnerBkg']/div[@id='RouteAddress_DIV1']/div[@class='sel_body']/div[@id='RADIV_BODY1']/div[@id='RADiv_ResItem1']/div[@id='RA_ResItem_1']/table/tbody/tr[1]/td[2]").click()
    except:
        a = 1
    else:
        time.sleep(2)
    try:
        driver.find_element_by_xpath(
            "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/ul[@id='cards-level1']/li[1]/div[@class='RouteAddressOuterBkg']/div[@class='RouteAddressInnerBkg']/div[@id='RouteAddress_DIV0']/div[@class='sel_body']/div[@id='RADIV_BODY0']/div[@id='RADiv_ResItem0']/div[@id='RA_ResItem_0']/table/tbody/tr[1]/td[2]").click()
    except:
        a = 1
    # 出现模糊地址的时候选择第一个准确地址

    time.sleep(2)
    try:  # 超时异常处理
        WebDriverWait(driver, 5, 0.5).until(EC.presence_of_element_located((By.XPATH,
                                                                            "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/ul[@id='cards-level1']/li[1]/div[@id='nav_container']/div[@class='route_contentWrapper walk_cont']/div[@id='route_content_walk']/div[@class='special']/div[@class='drive']/div[@class='con']/div[@class='navtrans-navlist-view active expand navtrans-type-walk']/div[@class='navtrans-navlist-title']/p[@class='navtrans-navlist-title-p title-info']/span[@class='last']")))
    except:
        driver.find_element_by_xpath(
            "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/div[@id='searchbox']/button[@id='search-button']").click()
        try:
            driver.find_element_by_xpath(
                "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/ul[@id='cards-level1']/li[1]/div[@class='RouteAddressOuterBkg']/div[@class='RouteAddressInnerBkg']/div[@id='RouteAddress_DIV1']/div[@class='sel_body']/div[@id='RADIV_BODY1']/div[@id='RADiv_ResItem1']/div[@id='RA_ResItem_1']/table/tbody/tr[1]/td[2]").click()
        except:
            a = 1
        time.sleep(2)
        try:
            driver.find_element_by_xpath(
                "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/ul[@id='cards-level1']/li[1]/div[@class='RouteAddressOuterBkg']/div[@class='RouteAddressInnerBkg']/div[@id='RouteAddress_DIV0']/div[@class='sel_body']/div[@id='RADIV_BODY0']/div[@id='RADiv_ResItem0']/div[@id='RA_ResItem_0']/table/tbody/tr[1]/td[2]").click()
        except:
            a = 1
    try:
        span2 = driver.find_element_by_xpath(
            "/html/body[@class='pc']/div[@id='app']/div[@id='left-panel']/ul[@id='cards-level1']/li[1]/div[@id='nav_container']/div[@class='route_contentWrapper walk_cont']/div[@id='route_content_walk']/div[@class='special']/div[@class='drive']/div[@class='con']/div[@class='navtrans-navlist-view active expand navtrans-type-walk']/div[@class='navtrans-navlist-title']/p[@class='navtrans-navlist-title-p title-info']/span[@class='last']").get_attribute(
            'textContent')
    except:
        span2 = '-1'
    # 找到文字的信息
    span2 = transform(span2)
    print(span2, end=" ")


def transform(span):
    # 把文字转换为以米为单位的数字
    if span.find("公里") != -1:
        span = re.sub('公里', '', span)
        span = re.sub('约', '', span)
        span = int(float(span) * 1000)
    else:
        span = re.sub('约', '', span)
        span = re.sub('米', '', span)
        span = int(float(span))
    return span


location = ["中山大学(东校区)-牌坊", "中山大学(东校区)-软件学院", "中山大学东校区-国家超级计算广州中心", "中山大学东校区行政会议中心-A座", "中山大学(东校区)-停车场",
            "中山大学(东校区)-行政会议中心", "中山大学(东校区)公共教学楼-A座", "中山大学(东校区)行政会议中心-B座", "中山大学北学院楼", \
            "默园", "中山大学东校区-公共教学楼E", "三行情书林", "中山大学(东校区)-图书馆", "落雁台", "广州东校区教学实验中心-A座", "广州东校区教学实验中心-D座", \
            "中山大学(东校区)-传播与设计学院", "中山大学(东校区)-体育馆", "中山大学(东校区)-东田径场", "中山大学(东校区)-篮球场", "中山大学(东校区)-游泳池", "广州东校区西田径场",
            "中山大学-工学院校友回望林", \
            "中山大学东校区学生第一食堂", "至善学生活动中心", "格致园", "至善园", '慎思园', '明德园', '中山大学东校区学生公寓']

# for i in range(len(location)):
for j in range(len(location)):
    if (j == 10):
        print(0, end=" ")
    else:
        startSpide(location[10], location[j])
print('')

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

品尚公益团队

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值