簡體   English   中英

從網頁上的不同鏈接獲取信息,並使用pandas將其寫入.xls文件,在Python中使用bs4

[英]Fetching information from the different links on a web page and writing them to a .xls file using pandas,bs4 in Python

我是Python編程的初學者。 我在python中使用bs4模塊練習網頁抓取。

我從網頁中提取了一些字段,但它只提取了13個項目,而網頁有超過13個項目。 我無法理解為什么其他項目沒有被提取出來。

另一件事是我想提取網頁上每個項目的聯系電話和電子郵件地址,但它們可以在項目的相應鏈接中找到。 我是初學者,坦率地說,我一直堅持如何訪問和抓取給定網頁中每個項目的單個網頁的鏈接。 請告訴我在哪里做錯了,如果可能的話,建議做什么。

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd


res = requests.post('https://www.nelsonalexander.com.au/real-estate-agents/?office=&agent=A')
soup = bs(res.content, 'lxml')

data = soup.find_all("div",{"class":"agent-card large large-3 medium-4 small-12 columns text-center end"})

records = []

for item in data:
    name = item.find('h2').text.strip()
    position = item.find('h3').text.strip()
    records.append({'Names': name, 'Position': position})

df = pd.DataFrame(records,columns=['Names','Position'])
df=df.drop_duplicates()
df.to_excel(r'C:\Users\laptop\Desktop\NelsonAlexander.xls', sheet_name='MyData2', index = False, header=True)

我已經完成了上面的代碼,只是提取每個項目的名稱和位置,但它只刪除了13條記錄,但記錄的數量超過了網頁中的記錄。 我無法編寫任何代碼來提取每個記錄的聯系號碼和電子郵件地址,因為它存在於每個項目的單個頁面中,因為我已經卡住了。

Excel工作表如下所示:

在此輸入圖像描述

該網站在滾動時動態加載列表,但您可以跟蹤ajax請求,並直接解析數據:

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0', 'Referer': 'https://www.nelsonalexander.com.au/real-estate-agents/?office=&agent=A'}
records = []

with requests.Session() as s:

    for i in range(1, 22):

        res = s.get(f'https://www.nelsonalexander.com.au/real-estate-agents/page/{i}/?ajax=1&agent=A', headers=headers)
        soup = bs(res.content, 'lxml')

        data = soup.find_all("div",{"class":"agent-card large large-3 medium-4 small-12 columns text-center end"})

        for item in data:
            name = item.find('h2').text.strip()
            position = item.find('h3').text.strip()
            phone = item.find("div",{"class":"small-6 columns text-left"}).find("a").get('href').replace("tel:", "")
            records.append({'Names': name, 'Position': position, 'Phone': phone})

df = pd.DataFrame(records,columns=['Names','Position', 'Phone'])
df=df.drop_duplicates()
df.to_excel(r'C:\Users\laptop\Desktop\NelsonAlexander.xls', sheet_name='MyData2', index = False, header=True)

我確信電子郵件不在DOM中。 我對@drec4s代碼做了一些修改,直到沒有條目(動態)。

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
import itertools

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0', 'Referer': 'https://www.nelsonalexander.com.au/real-estate-agents/?office=&agent=A'}
records = []

with requests.Session() as s:


    for i in itertools.count():

        res = s.get('https://www.nelsonalexander.com.au/real-estate-agents/page/{}/?ajax=1&agent=A'.format(i), headers=headers)
        soup = bs(res.content, 'lxml')

        data = soup.find_all("div",{"class":"agent-card large large-3 medium-4 small-12 columns text-center end"})
        if(len(data) > 0):
            for item in data:
                name = item.find('h2').text.strip()
                position = item.find('h3').text.strip()
                phone = item.find("div",{"class":"small-6 columns text-left"}).find("a").get('href').replace("tel:", "")
                records.append({'Names': name, 'Position': position, 'Phone': phone})
                print({'Names': name, 'Position': position, 'Phone': phone})
        else:
            break

暫無
暫無

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

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