无法通过Python使用beautifulSoup获得商店列表

问题描述

我有一个代码,应该给我商店数据的列表。但是该列表为空,并且没有显示任何错误...任何想法如何做到这一点?

import requests
from bs4 import BeautifulSoup 
import pandas as pd

def get_page_data(number):
    print('number:',number)

    url = 'https://www.brw.pl/siec-sprzedazy/?page={}'.format(number)
    response = requests.get(url)
    soup = BeautifulSoup(response.content,'html.parser')

    container = soup.find(class_='lista-saloNow')
    items = container.find_all(class_='salon-kontener')


    dane = []

    for item in items:
        adres = item.find(class_='salon-szczegoly-adres').get_text(strip=True)
        dane.append([adres])

    return dane


wszystkie_dane = []
for number in range(1,3):
    dane_na_stronie = get_page_data(number)

    wszystkie_dane.extend(dane_na_stronie)

dane = pd.DataFrame(wszystkie_dane,columns=['adres'])
dane.to_csv('brw.csv',index=False)

解决方法

使用requests尝试以下方法,该方法干净,可靠并且需要较少的代码即可直接从提供的网站获取所需的结果。

  1. 首先,我在检查了Chrome的网络部分后从网站获取了API URL(ajax调用)。
  2. 执行GET请求以从API调用中获取数据。
  3. 将其转换为JSON。
  4. 最后遍历内容。

您可以在浏览器中单击URL,以查看结果将显示所有列,然后可以根据需要使用它们。现在,我以与获取其他列相同的方式在打印语句中仅获取5个。

import json
import requests
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

def scrap_shops_data():
    api_url = 'https://www.brw.pl/ajax/zpLIv5maeKSYy8KP07immqanj-PVnJO6mQ/' #API URL to fetch data in JSON form

    shops_result = requests.get(api_url,verify=False).json() #Get request to fetch the data from the supplied URL
    for shop in shops_result: #loop to iterate on the JSON object
        print('-' * 100)
        print(shop['nazwa_salonu'])
        print(shop['adres'])
        print(shop['kod_pocztowy'])
        print(shop['miejscowosc'])
        print(shop['email'])
        print('-' * 100)

scrap_shops_data()