如何从target.com产品页面抓取产品价格?

时间:2019-11-23 19:09:03

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

我最近了解了网络抓取,并希望创建一个程序来抓取每日产品价格。我在python中使用请求和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)

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

谢谢!

2 个答案:

答案 0 :(得分:2)

只要您具有商品/产品ID,就可以创建一个会话来获取本地商店ID,API密钥,然后从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

答案 1 :(得分:0)

您不希望刮擦html,而是希望刮擦嵌入的微数据或嵌入式的“ ld + json”数据。其中之一包含productid。有了该值后,将其插入“ redsky.target.com” API。...查看下面网址中的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可能会有帮助。