Beautifulsoup:从 a 到 z 迭代列表并解析数据以便将其存储在 df 中

问题描述 投票:0回答:1

我目前正在打造一个非常非常简单的解析器,它在成员列表上从a到z ::我们这里有一个成员列表:

参见:https://vvonet.vvo.at/vvonet_mitgliederverzeichnisneu

注意:我们必须打开链接“kontaktinformationen”并将其中的数据抓取到 pandas df

我认为我可以使用 python beautifulsoup 请求来做到这一点,并将其打印到屏幕或将其存储在 df 中。

首先,脚本应获取会员列表页面,提取各个会员页面的链接,访问每个会员的“kontaktinformationen”页面,然后提取联系信息。 最后,我认为最好将联系信息存储在 DataFrame 中。 好吧 - 我终于能够将 DataFrame 打印到屏幕上或将其保存到 CSV 文件中。

这是我的尝试:

import requests
from bs4 import BeautifulSoup
import pandas as pd

# first,  we send a GET request to the member list page
url = "https://vvonet.vvo.at/vvonet_mitgliederverzeichnisneu"
response = requests.get(url)

# here a check if the request was successful
if response.status_code == 200:
    # Parse the HTML content of the page
    soup = BeautifulSoup(response.content, "html.parser")
    
    # Find now all member links
    member_links = soup.find_all("a", class_="font1")
    
    # now - Initialize lists to store data
    member_data = []
    
    # Iterate over member links
    for member_link in member_links:
        # Get the URL of the "kontaktinformationen" page
        member_url = "https://vvonet.vvo.at" + member_link["href"] + "/kontaktinformationen"
        
        # Send a GET request to the member's "kontaktinformationen" page
        member_response = requests.get(member_url)
        
        # Check if the request was successful
        if member_response.status_code == 200:
            # Parse the HTML content of the page
            member_soup = BeautifulSoup(member_response.content, "html.parser")
            
            # Find the contact information section
            contact_info_div = member_soup.find("div", class_="contact")
            
            # Check if contact information section exists
            if contact_info_div:
                # Extract the contact information
                contact_info_text = contact_info_div.get_text(separator="\n", strip=True)
                member_data.append(contact_info_text)
            else:
                member_data.append("Contact information not found")
        else:
            member_data.append(f"Failed to retrieve contact information for {member_link.text.strip()}")
    
    # Create a DataFrame
    df = pd.DataFrame(member_data, columns=["Contact Information"])
    
    # Display the DataFrame
    print(df)
    
    # Alternatively, you can save the DataFrame to a CSV file
    # df.to_csv("member_contact_information.csv", index=False)
else:
    print("Failed to retrieve the member list page.")

但此刻我得到一个空数据框..

Empty DataFrame
Columns: [Contact Information]
Index: []
python pandas dataframe request
1个回答
0
投票

首先减少复杂性的步骤是相当容易的。
对您要访问的 URL 进行硬编码。
测试您的请求返回的结果。
完成后,评估您的请求,使用漂亮的汤库来检查公共的特定字段。
再次检查结果。
然后将它们放入 pandas 数据框中。

不要一步做三件事(这显然可能是可怕的错误)。

© www.soinside.com 2019 - 2024. All rights reserved.