【问题标题】:Not able to scrape html table from a website using python script无法使用 python 脚本从网站上抓取 html 表
【发布时间】:2020-02-25 08:17:53
【问题描述】:

我实际上是在尝试抓取link 中显示的表格中的"Name" 列并将其保存为 csv 文件。

我写了一个如下的python脚本:

from bs4 import BeautifulSoup
import requests
import csv


# Step 1: Sending a HTTP request to a URL
url = "https://myaccount.umn.edu/lookup?SET_INSTITUTION=UMNTC&type=name&CN=University+of+Minnesota&campus=a&role=any"
# Make a GET request to fetch the raw HTML content
html_content = requests.get(url).text


# Step 2: Parse the html content
soup = BeautifulSoup(html_content, "lxml")
# print(soup.prettify()) # print the parsed data of html


# Step 3: Analyze the HTML tag, where your content lives
# Create a data dictionary to store the data.
data = {}
#Get the table having the class wikitable
gdp_table = soup.find("table")
gdp_table_data = gdp_table.find_all("th")  # contains 2 rows

# Get all the headings of Lists
headings = []
for td in gdp_table_data[0].find_all("td"):
    # remove any newlines and extra spaces from left and right
    headings.append(td.b.text.replace('\n', ' ').strip())

# Get all the 3 tables contained in "gdp_table"
for table, heading in zip(gdp_table_data[1].find_all("table"), headings):
    # Get headers of table i.e., Rank, Country, GDP.
    t_headers = []
    for th in table.find_all("th"):
        # remove any newlines and extra spaces from left and right
        t_headers.append(th.text.replace('\n', ' ').strip())

    # Get all the rows of table
    table_data = []
    for tr in table.tbody.find_all("tr"): # find all tr's from table's tbody
        t_row = {}
        # Each table row is stored in the form of
        # t_row = {'Rank': '', 'Country/Territory': '', 'GDP(US$million)': ''}

        # find all td's(3) in tr and zip it with t_header
        for td, th in zip(tr.find_all("td"), t_headers): 
            t_row[th] = td.text.replace('\n', '').strip()
        table_data.append(t_row)

    # Put the data for the table with his heading.
    data[heading] = table_data
    print("table_data")

但是当我运行这个脚本时,我什么也得不到。 请帮我解决这个问题

【问题讨论】:

  • 您是否尝试过使用调试器或仅打印变量以查看值是否正确?在我尝试运行您的脚本后,gdp_table_data 的值是[<th>Name</th>, <th>Email</th>, <th>Work Phone</th>, <th>Phone</th>, <th>Dept/College</th>]。是你所期望的吗?
  • 是的,我需要该网站的所有名称,您能帮我实现吗
  • @SSC 只命名而不是电子邮件和其他

标签: python python-3.x beautifulsoup python-requests


【解决方案1】:

您的列表 gdp_table_data[0].find_all("td") 似乎是空的,因此说明您没有找到任何东西(您的 for 循环没有做任何事情)。如果没有更多关于您的策略的背景信息,就很难提供帮助。

顺便说一句,如果您不反对使用外部库,那么使用pandas 会非常容易抓取此类网页。让您知道:

>>> import pandas as pd
>>> url = "https://myaccount.umn.edu/lookup?SET_INSTITUTION=UMNTC&type=name&CN=University+of+Minnesota&campus=a&role=any"
>>> df = pd.read_html(url)[0]
>>> print(df)
                                                  Name              Email  Work Phone  Phone          Dept/College
 0      AIESEC at the University of Minnesota (aiesec)     aiesec@umn.edu         NaN    NaN  Student Organization
 1   Ayn Rand Study Group University of Minnesota (...    aynrand@umn.edu         NaN    NaN                   NaN
 2                               Balance UMD (balance)  balance@d.umn.edu         NaN    NaN  Student Organization
 3   Christians on Campus the University of Minneso...     cocumn@umn.edu         NaN    NaN  Student Organization
 4          Climb Club University of Minnesota (climb)      climb@umn.edu         NaN    NaN  Student Organization
 ..                                                ...                ...         ...    ...                   ...
 74   University of Minnesota Tourism Center (tourism)    tourism@umn.edu         NaN    NaN            Department
 75  University of Minnesota Treasury Accounting (t...   treasury@umn.edu         NaN    NaN            Department
 76  University of Minnesota Twin Cities HOSA (umnh...    umnhosa@umn.edu         NaN    NaN  Student Organization
 77           University of Minnesota U Write (uwrite)                NaN         NaN    NaN            Department
 78        University of Minnesota VoiceMail (cs-vcml)    cs-vcml@umn.edu         NaN    NaN  OIT Network & Design

 [79 rows x 5 columns]

现在,只获取名称非常简单:

>>> print(df.Name)
0        AIESEC at the University of Minnesota (aiesec)
1     Ayn Rand Study Group University of Minnesota (...
2                                 Balance UMD (balance)
3     Christians on Campus the University of Minneso...
4            Climb Club University of Minnesota (climb)
                            ...
74     University of Minnesota Tourism Center (tourism)
75    University of Minnesota Treasury Accounting (t...
76    University of Minnesota Twin Cities HOSA (umnh...
77             University of Minnesota U Write (uwrite)
78          University of Minnesota VoiceMail (cs-vcml)
Name: Name, Length: 79, dtype: object

要仅将该列导出到.csv,请使用:

>>> df[["Name"]].to_csv("./filename.csv")

【讨论】:

  • 我只想获取名称列如何实现?
  • 编辑了我的答案。一个简单的df.Name.tolist() 就可以了。
  • 当我将它保存在 .py 文件中并运行时,我实际上没有得到任何东西,我需要它作为脚本
  • 如果您想使用脚本打印列表,可以使用print(df.Name.tolist())
  • 不,我希望将这些名称上传到另一个 csv 文件
猜你喜欢
  • 1970-01-01
  • 2013-12-05
  • 2021-09-23
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多