1 回答

TA貢獻(xiàn)1853條經(jīng)驗 獲得超6個贊
看起來您正在執(zhí)行許多 find_all 操作,然后將它們拼接在一起。我的建議是做一個 find_all 然后迭代它。當(dāng)所有數(shù)據(jù)都在一個地方時,它可以更容易地構(gòu)建數(shù)據(jù)框的列。
我已更新以下代碼以成功提取鏈接而不會出錯。對于任何代碼,都有多種方法可以執(zhí)行相同的任務(wù)。這可能不是最優(yōu)雅的,但它確實完成了工作。
import requests
from bs4 import BeautifulSoup
import pandas as pd
r = 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 = BeautifulSoup(r.text, 'html.parser')
get_cards = soup.find_all("div",{"class":"card horizontal-split vcard"})
agent_list = []
for item in get_cards:
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').a['href']
try:
email = item.find('a',class_='val withicon')['href'].replace('mailto:','')
except:
email = 'No Email address'
agent_list.append({'name':name,'position':position,'email':email,'link':link})
df = pd.DataFrame(agent_list)
以上是我為創(chuàng)建數(shù)據(jù)框而放在一起的一些示例代碼。這里的關(guān)鍵是做一個 find_all"class":"card horizontal-split vcard"}
希望有所幫助。
干杯,亞當(dāng)
添加回答
舉報