Ваш код занимает много времени, потому что во втором цикле он добавляется к записям во время итерации, вызывая расширение цикла с каждой итерацией. Чтобы исправить ваш код, вам нужно изменить имя переменной во втором цикле.
Таким образом, вместо использования переменной "records" во втором цикле, вот так:
records.append({'Names': nl, 'Position': pl, 'Email': el, 'Phone': phl})
изменить его имя на что-то вроде «unique_records»:
unique_records.append({'Names': nl, 'Position': pl, 'Email': el, 'Phone': phl})
Вот полностью обновленный код:
from bs4 import BeautifulSoup as bs
import pandas as pd
import requests
res = requests.get('https://www.raywhite.com/contact/?type=People&target=people&suburb=Sydney%2C+NSW+2000&radius=50%27%27&firstname=&lastname=&_so=contact', headers = {'User-agent': 'Super Bot 9000'})
soup = bs(res.content, 'lxml')
data = soup.find_all("div",{"class":"card horizontal-split vcard"})
records = []
unique_records = []
for item in data:
name = item.find('li', class_='agent-name').text
position = item.find('li',class_='agent-role').text
phone = item.find('li', class_='agent-officenum').text
#link = item.find('li', class_='agent-name')['href']
try:
email = item.find('a', class_='val withicon')['href']
except:
email = 'No Email address'
records.append({'Names':name,'Position':position,'Email':email,'Phone':phone})
for i in records:
nl=pd.unique(name).tolist()
pl=pd.unique(position).tolist()
el=pd.unique(email).tolist()
phl=pd.unique(phone).tolist()
unique_records.append({'Names': nl, 'Position': pl, 'Email': el, 'Phone': phl})
df = pd.DataFrame(unique_records,columns=['Names','Position','Phone','Email'])
df.to_excel(r'C:\Users\laptop\Desktop\RayWhite.xls', sheet_name='MyData2', index = False, header=True)