簡體   English   中英

使用Python中的Pandas模塊將網站的提取項寫入具有不同長度列表的.xls表中

[英]Writing extracted items of from a website onto a .xls sheet with lists of different length using Pandas module in Python

我是Python編程的初學者,我正在練習從網站抓取不同的值。 我已經從特定網站提取了項目,現在想將它們寫到.xls文件中。

整個網頁有714條記錄,其中包括重復記錄,但是由於zip()函數在最小的列表用盡時會停止,因此excel工作表僅顯示707條記錄。 這里最小的列表是電子郵件列表。 因此,由於zip()函數的屬性,它變得精疲力盡,並且迭代停止。我什至在沒有電子郵件地址的記錄的if條件下檢查它,以便顯示“沒有電子郵件地址”,但仍然704與重復的記錄一起顯示相同的結果。 請告訴我我要去哪里錯了,如果可能的話,建議有關刪除重復記錄並在沒有電子郵件的地方顯示“沒有電子郵件地址”的處理方法。

from bs4 import BeautifulSoup as bs
import pandas as pd

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')

names=[]
positions=[]
phone=[]
emails=[]
links=[l1['href'] for l1 in soup.select('.agent-name a')]

nlist = soup.find_all('li', class_='agent-name')
plist= soup.find_all('li',class_='agent-role')
phlist = soup.find_all('li', class_='agent-officenum')
elist = soup.find_all('a',class_='val withicon')

for n1 in nlist:
    names.append(n1.text)
for p1 in plist:
    positions.append(p1.text)
for ph1 in phlist:
    phone.append(ph1.text)
for e1 in elist:
    emails.append(e1.get('href') if e1.get('href') is not None else 'No Email address')


df = pd.DataFrame(list(zip(names,positions,phone,emails,links)),columns=['Names','Position','Phone','Email','Link'])
df.to_excel(r'C:\Users\laptop\Desktop\RayWhite.xls', sheet_name='MyData2', index = False, header=True)

excel工作表如下所示,我們可以在其中看到最后的記錄名稱,並且其電子郵件地址不匹配:

射線白Excel工作表

射線白Excel工作表

看來您正在執行許多find_all,然后將它們縫合在一起。 我的建議是做一個find_all然后遍歷。 當所有數據都放在一個位置時,構建數據框的列變得容易得多。

我已經更新了以下代碼,以成功提取鏈接而沒有錯誤。 使用任何代碼,都有許多方法可以執行相同的任務。 這可能不是最優雅的,但確實可以完成工作。

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)

上面是一些我用來創建數據框的示例代碼。 此處的關鍵是在"class":"card horizontal-split vcard"}上執行一個find_all "class":"card horizontal-split vcard"}

希望對您有所幫助。

干杯,亞當

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM