【问题标题】:Python Request Taking Much Longer Than ExpectedPython 请求花费的时间比预期的要长得多
【发布时间】:2020-05-26 17:20:50
【问题描述】:

我正在尝试从返回 JSON 文件的 URL 中抓取。

页面在我的浏览器上加载不到一秒,但使用请求大约需要 10 秒。关于为什么需要这么长时间以及如何改变它的任何建议?

import requests
from bs4 import BeautifulSoup
import json
import pandas as pd

URL = 'https://www.lowes.com/IntegrationServices/resources/storeLocator/json/v2_0/stores?langId=-1&storeId=10702&catalogId=10051&place=10001&count=25'

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"}
page = requests.get(URL, headers=headers )
soup = BeautifulSoup(page.content, 'html.parser')
site_json = json.loads(soup.text)


df = pd.DataFrame.from_dict(site_json)

first_row = pd.Series(df.iloc[0]['Location'])

print(first_row)

(我也知道在将其转换为数据库时我可能会执行额外的步骤,我习惯于从 HTML 中抓取......这仍然有效)

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    对我来说,更改用户代理似乎可以解决问题,例如:

    headers = {
        "User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36"
    }
    

    也许问题与 Lowes 的 API 服务器拒绝或延迟对无法识别/不常见的用户代理的响应有关。可以在here 找到当前 Chrome 用户代理值的列表。

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      相关资源
      最近更新 更多