带有漂亮汤的Python数据收集-从href内获取数据

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

我是Python的新手,并且开始了解Beautiful Soup。所以我有一个问题:我需要从活动公司获取数据,特别是联系数据。他们的主表包含所有参与者的姓名和位置。但是,要获取联系数据(电话,电子邮件),您需要按一下表中的每个公司名称,它会打开包含所有其他信息的新窗口。我正在寻找一种从href获取信息并将其与主表中的数据组合的方法。

所以我可以获取表格和所有href:

from bs4 import BeautifulSoup as soup
from urllib.request import urlopen


test_url = "https://standconstruction.messe-duesseldorf.de/vis/v1/en/hallindex/1.09?oid=2656&lang=2"
test_data = urlopen(test_url)
test_html = test_data.read()
test_data.close()

page_soup = soup(test_html, "html.parser")

test_table = page_soup.findAll("div", {"class": "exh-table-col"})
print(test_table)

结果,我得到了所有表格并获得了这类信息(例如一行的示例),包括名称,地址和href:

<a class="flush" href="/vis/v1/en/exhibitors/aluminium2020.2661781?oid=2656&amp;lang=2">
<h2 class="exh-table-item__name" itemprop="name">Aerospace Engineering Equipment (Suzhou) Co LTD</h2>
</a>

</div>, <div class="exh-table-col exh-table-col--address">
<span class=""><i class="fa fa-map-marker"></i>  <span class="link-fix--text">Hall 9 / G57</span></span>

这是我的问题开始的地方,我不知道如何从href中获取其他数据并将其与主数据结合。

我将非常感谢任何可能的解决方案,或者至少是一个技巧,我可以在哪里找到答案。

更新问题:我需要一个包含以下各列信息的表:1.姓名; 2.礼堂3.PDF; 4.电话; 5,电子邮件

[如果您手工收集数据-要获取电话和电子邮件,您需要单击相应的链接以显示它。我想知道是否有一种方法可以从这些链接中导出电话和电子邮件,并使用Python将它们添加到前3列中。

python web-scraping beautifulsoup href
1个回答
0
投票
import requests
from bs4 import BeautifulSoup
import pandas as pd
from time import sleep

params = {
    "oid": "2656",
    "lang": "2"
}


def main(url):
    with requests.Session() as req:
        r = req.get(url, params=params)
        soup = BeautifulSoup(r.content, 'html.parser')

        target = soup.select("div.exh-table-item")

        names = [name.h2.text for name in target]
        hall = [hall.span.text.strip() for hall in target]
        pdf = [pdf.select_one("a.color--darkest")['href'] for pdf in target]
        links = [f"{url[:46]}{link.a['href']}" for link in target]

        phones = []
        emails = []

        for num, link in enumerate(links):
            print(f"Extracting {num +1} of {len(links)}")

            r = req.get(link)

            soup = BeautifulSoup(r.content, 'html.parser')
            goal = soup.select_one("div[class^=push--bottom]")

            try:
                phone = goal.select_one("span[itemprop=telephone]").text
            except:
                phone = "N/A"

            try:
                email = goal.select_one("a[itemprop=email]").text
            except:
                email = "N/A"

            emails.append(email)
            phones.append(phone)
            sleep(1)

        df = pd.DataFrame(list(zip(names, hall, pdf, phones, emails)), columns=[
                          "Name", "Hall", "PDF", "Phone", "Email"])
        print(df)
        df.to_csv("data.csv", index=False)


main("https://standconstruction.messe-duesseldorf.de/vis/v1/en/hallindex/1.09")

输出:View Online

enter image description here

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