Веб-скребковый вывод "itemprop" - PullRequest
0 голосов
/ 17 октября 2019

Привет, я написал следующий код, чтобы получить местоположение города.

import requests
from bs4 import BeautifulSoup

#Loads the webpage
r = requests.get("https://www.century21.com/for-sale-homes/Westport-CT-20647c", headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})
#grabs the contect of this page
c=r.content

if "blocked" in r.text:
    print ("we've been blocked")



#makes the content more readable
soup=BeautifulSoup(c,"html.parser")

#Prints out the content 
#print(soup.prettify())

#Finds the number of proterty Listed
all=soup.find_all("div", {"class":"sr-card js-safe-link"})

#Finds the city of the property of interest
x=all[1].find("div", {"class":"sr-card__city-state"})




for itemprop in x:
        print(x.find("span", itemprop="addressLocality").text)

Вывод x выглядит следующим образом

<div class="sr-card__city-state">
<span itemprop="addressLocality">Westport</span>,
            <span itemprop="addressRegion">CT</span>
<span itemprop="postalCode">06880</span>
</div>

когда выполняется цикл for, я получаюследующий вывод

Westport
Westport
Westport
Westport
Westport
Westport
Westport

Пока он печатает правильный вывод, я не понимаю, почему его выводят 7 раз. Я понимаю, что я делаю ошибку, но я не понимаю, где я делаю ошибку. Я был бы очень признателен, если кто-то может указать в правильном направлении.

Спасибо

1 Ответ

0 голосов
/ 18 октября 2019

Длина x равна 7, и именно поэтому она показывает выходной результат 7 раз. Вы можете попробовать что-то вроде этого,

#Finds the number of proterty Listed
all=soup.find_all("div", {"class":"sr-card js-safe-link"})

#Finds the city of the property of interest
x=all[1].find("div", {"class":"sr-card__city-state"})

print(x)

print(len(x)) # Length of x

for prop in x.find("span", itemprop="addressLocality"):
        print(prop)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...