BS4:Python 网页抓取中的属性错误

BS4: Attribute Error in Web Scraping with Python

我需要从这个网站中提取 link 商店所在城市的名称。我创建了这段代码:

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

    url = 'https://www.biedronka.pl/pl/sklepy/lista,lat,52.25,lng,21,page,'.format(number)
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    container = soup.find(class_='s-content shop-list-page')
    items = container.find_all(class_='shopListElement')

    dane = []
    for item in items:
        miasto = item.find(class_='h4').get_text(strip=True)
        adres = item.find(class_='shopFullAddress').get_text(strip=True)
        dane.append([adres])

    return dane

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

    wszystkie_dane.extend(dane_na_stronie)

dane = pd.DataFrame(wszystkie_dane, columns=['miasto','adres'])

dane.to_csv('biedronki_lista.csv', index=False)

问题出现在:

   miasto = item.find(class_='h4').get_text(strip=True)
AttributeError: 'NoneType' object has no attribute 'get_text'

关于如何从此网站提取城市名称(在 h4 中)的任何想法?

尝试使用:

miasto = item.find('h4').text.split()[0]

或:

miasto = item.find('h4').get_text(strip=True)

注:

"h4" is a tag, not a class.


解释:

  • 当你给.find('h4')时,它returns:
<h4 style="margin-bottom: 10px;">

                Rzeszów             <span class="shopFullAddress">ul.<span class="shopAddress"> </span></span>
  • 当你给.text时,它returns:
'Rzeszów            \tul.'
  • 当你给 .split() 时,它 returns:
['Rzeszów', 'ul.']
  • 从这里我们得到了我们需要的东西。

因此,只要您在此代码中遇到错误,就执行此操作。

dane = []
    for item in items:
        miasto = item.find('h4').get_text(strip=True)
        adres = item.find('shopFullAddress').get_text(strip=True)
        dane.append([adres])

class_='h4' 是您将标签名称传递给 class 的属性,这是不正确的:

miasto = item.find('h4').get_text(strip=True)