【问题标题】:How do I scrape the product price from target.com product page?如何从 target.com 产品页面抓取产品价格?
【发布时间】:2019-11-23 19:09:03
【问题描述】:

我最近了解了网络抓取,并想创建一个抓取每日产品价格的程序。我在 python 中使用 requests 和 bs4 来抓取 target.com。到目前为止,这是我的代码:

TIMES = [2, 3, 4, 5, 6, 7]

url = 'https://www.target.com/p/dyson-ball-animal-2-upright-vacuum-iron-purple/-/A-52190951'
sleep(choice(TIMES))
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

sleep(choice(TIMES))
name = soup.find('h1').get_text().strip().replace(',', ';')
print('Product name: ', name)

sleep(choice(TIMES))
current_price = soup.find('span', {'data-test': 'product-savings'})
print('Current price: ', current_price)

当我运行我的代码时,产品名称是正确的,但当前价格始终是“无”。我应该以其他方式搜索产品价格吗?

提前致谢!

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup python-requests


    【解决方案1】:

    只要你有item/product ID,你就可以创建一个session来获取本地store id,api key,然后从API中获取:

    import pandas as pd
    import requests
    
    s = requests.session()
    s.get('https://www.target.com')
    
    key = s.cookies['visitorId']
    location = s.cookies['GuestLocation'].split('|')[0]
    
    store_id = requests.get('https://redsky.target.com/v3/stores/nearby/%s?key=%s&limit=1&within=100&unit=mile' %(location, key)).json()
    store_id = store_id[0]['locations'][0]['location_id']
    
    product_id = '52190951'
    url = 'https://redsky.target.com/web/pdp_location/v1/tcin/%s' %product_id
    payload = {
    'pricing_store_id': store_id,
    'key': key}
    
    
    jsonData = requests.get(url, params=payload).json()
    df = pd.DataFrame(jsonData['price'], index=[0])
    

    输出:

    print (df.to_string())
           tcin  location_id  reg_retail  current_retail current_retail_start_timestamp current_retail_end_timestamp  default_price formatted_current_price formatted_current_price_type  is_current_price_range
    0  52190951         3991      499.99          499.99           2019-10-19T07:00:00Z         9999-12-31T00:00:00Z          False                 $499.99                          reg                   False
    

    【讨论】:

    • 感谢您这么快回答!有没有办法查看一般的价格而不是特定的商店 ID?是目标 API 的链接吗?您将如何改变它们以查看不同的产品?
    • 那么 api 需要一个商店/位置 ID。至于产品 id,我相信也有办法得到它,但还没有研究在哪里可以找到这些数据。但是你只需要改变产品是可变的。
    • 如何访问目标 API?它仅对员工或受信任的第三方显示..
    【解决方案2】:

    您不想抓取 html,您想要抓取嵌入的微数据或嵌入的“ld+json”数据。其中之一包含 productid。获得该值后,将其插入 'redsky.target.com' api....查看下面 url 中的 productid 值?

    https://redsky.target.com/v2/pdp/tcin/52190951?excludes=taxonomy,promotion,bulk_ship,rating_and_review_reviews,rating_and_review_statistics,question_answer_statistics

    …然后解析返回的json得到价格。

    This 可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 2016-03-16
      • 2019-04-04
      相关资源
      最近更新 更多