[英]BS4: Attribute Error in Web Scraping with Python
我需要從該網站中提取商店所在城市的鏈接名稱。 我創建了這段代碼:
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 中)?
class_='h4'
是您將標簽名稱傳遞給 class 的屬性,這是不正確的:
miasto = item.find('h4').get_text(strip=True)
嘗試使用:
miasto = item.find('h4').text.split()[0]
或者:
miasto = item.find('h4').get_text(strip=True)
筆記:
“h4”是一個標簽,而不是 class。
解釋:
<h4 style="margin-bottom: 10px;">
Rzeszów <span class="shopFullAddress">ul.<span class="shopAddress"> </span></span>
.text
時,它會返回:'Rzeszów \tul.'
['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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.