首页 > 解决方案 > Requests 只获取网站源代码的一部分

问题描述

我正在尝试抓取 target.com,它似乎只解析了网站的一部分而没有产品(主要部分)。我的代码非常适合沃尔玛,但这个网站不...

我的代码:

res = requests.get(f'https://www.target.com/s?searchTerm=mask')
    print(res)  # Prints 200
    try: 
      res.raise_for_status()
    except requests.exceptions.HTTPError as e: 
      print('Connection Error')  # In case the connection fails

    else:
      soup = BeautifulSoup(res.text, "html.parser")
      print(soup.find_all('li', class_='Col-favj32-0 diyyNr h-padding-a-none h-display-flex', limit = 5))

如果我打印 soup.prettify() 它会打印网站的一部分,但没有产品......我知道它可以与 Selenium 一起使用,我尝试过,但需要它在没有它的情况下工作。

标签: pythonbeautifulsouppython-requests

解决方案


您在页面上看到的有关产品的数据是从外部 URL 加载的。您可以使用requests/ jsonmodules 来加载这些数据。

例如:

import json
import requests


kw = 'mask'
url = 'https://redsky.target.com/v2/plp/search/?channel=web&count=96&keyword={kw}&offset=0&pricing_store_id=3991&key=ff457966e64d5e877fdbad070f276d18ecec4a01'

data =  requests.get(url.format(kw=kw)).json()

# uncomment this to print all data;
# print(json.dumps(data, indent=4))

# print some data to screen
for i in data['search_response']['items']['Item']:
    print('{:<60} {}'.format(i['title'], i['price']['formatted_current_price']))

印刷:

2pk Adult Fabric Face Mask                                   $4.00
ICU Non Medical Face Mask 20ct                               $15.99
Adult 2pk Fabric Face Mask - Colors May Vary                 $5.00
Kids&#39; 2pk Fabric Face Masks - Colors May Vary            $5.00
Intco Non-medical Disposable Face Mask - 10ct                $8.99
Cetaphil Pro Derma Control Purifying Clay Mask - 3oz         $15.99
Jurassic World Velociraptor "Blue" Chomp 'N Roar Mask        $29.99
Pixi DetoxifEYE Facial Treatment - 60ct                      $24.00

...and so on.

推荐阅读