【发布时间】: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