繁体   English   中英

使用 Python 抓取 Uber 价格估算器页面

[英]Web scraping the Uber price estimator page using Python

所以我对网络抓取真的很陌生,我想构建一个机器人来检查一段时间内从 A 点到 B 点的 Uber 乘车价格。 我使用 Selenium 库来输入取货地点和目的地,现在我想从页面上抓取结果估计价格。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# Initialize webdriver object
firefox_webdriver_path = '/usr/local/bin/geckodriver'
webdriver = webdriver.Firefox(executable_path=firefox_webdriver_path)

webdriver.get('https://www.uber.com/global/en/price-estimate/')

time.sleep(3)

# Find the search box
elem = webdriver.find_element_by_name('pickup')
elem.send_keys('name/of/the/pickup/location')

time.sleep(1)
elem.send_keys(Keys.ENTER)

time.sleep(1)
elem2 = webdriver.find_element_by_name('destination')
elem2.send_keys('name/of/the/destination')

time.sleep(1)
elem2.send_keys(Keys.ENTER)
time.sleep(5)

elem3 = webdriver.find_element_by_class_name('bn rw bp nk ih cr vk')
print(elem3.text)

不幸的是,有一个错误:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .bn rw bp nk ih cr vk

而且我似乎无法找到解决方案。 在检查页面时,保存价格的类的名称具有以下名称“bn rw bp nk ih cr vk”,经过一些搜索,我发现这可能是 Javascript 而不是 HTML。 (我还要指出我对它们并不熟悉。)

检查页面

最终,我认为我可以使用 BeautifulSoup 和 requests 模块,但遇到了另一个错误。

import requests
from bs4 import BeautifulSoup
import re
import json

response = requests.get('https://www.uber.com/global/en/price-estimate/')
print(response.status_code)
406

我还尝试更改用户代理以解决此 HTTP 错误消息,但没有成功。 我不知道如何解决这个问题。

不完全是你需要的。 但我最近做了一个类似的应用程序,我会提供你需要的部分功能。 您唯一需要的是获取纬度和经度。 我为此使用了 google_places 提供商,但我确信有很多免费服务。

import requests
import json


def get_ride_price(origin_latitude, origin_longitude, destination_latitude, destination_longitude):
    url = "https://www.uber.com/api/loadFEEstimates?localeCode=en"

    payload = json.dumps({
      "origin": {
        "latitude": origin_latitude,
        "longitude": origin_longitude
      },
      "destination": {
        "latitude": destination_latitude,
        "longitude": destination_longitude
      },
      "locale": "en"
    })
    headers = {
      'content-type': 'application/json',
      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
      'x-csrf-token': 'x'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    result = [[x['vehicleViewDisplayName'], x['fareString']] for x in response.json()['data']['prices']]
    return result


print(get_ride_price(51.5072178, -0.1275862, 51.4974948, -0.1356583))

输出:

[['Assist', '£13.84'], ['Access', '£13.84'], ['Green', '£13.86'], ['UberX', '£14.53'], ['Comfort', '£16.02'], ['UberXL', '£17.18'], ['Uber Pet', '£17.77'], ['Exec', '£20.88'], ['Lux', '£26.32']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM