【发布时间】:2019-06-14 05:28:18
【问题描述】:
我正在尝试解析这个Link 以搜索结果
请选择:
- 学校=全部
- 运动=足球
- 会议=全部
- 年份=2005-2006
- 状态=全部
此搜索结果包含 226 个条目,我想解析所有 226 个条目并将其转换为 pandas 数据帧,以便数据帧包含“School”、“Conference”、“GSR”、“FGR”和“State”。所以,到目前为止,我能够解析表格标题,但我无法解析表格中的数据。请提供代码和解释。
注意:我是 Python 和 Beautifulsoup 的新手。
到目前为止我尝试过的代码:
url='https://web3.ncaa.org/aprsearch/gsrsearch'
#Create a handle, page, to handle the contents of the website
page = requests.get(url)
#Store the contents of the website under doc
doc = lh.fromstring(page.content)
#Parse data that are stored between <tr>..</tr> of HTML
tr_elements = doc.xpath('//tr')
#Create empty list
col=[]
i=0
#For each row, store each first element (header) and an empty list
for t in tr_elements[0]:
i+=1
name=t.text_content()
print ('%d:"%s"'%(i,name))
col.append((name,[]))
#Since out first row is the header, data is stored on the second row onwards
for j in range(1,len(tr_elements)):
#T is our j'th row
T=tr_elements[j]
#If row is not of size 10, the //tr data is not from our table
if len(T)!=10:
break
#i is the index of our column
i=0
#Iterate through each element of the row
for t in T.iterchildren():
data=t.text_content()
#Check if row is empty
if i>0:
#Convert any numerical value to integers
try:
data=int(data)
except:
pass
#Append the data to the empty list of the i'th column
col[i][1].append(data)
#Increment i for the next column
i+=1
Dict={title:column for (title,column) in col}
df=pd.DataFrame(Dict)
【问题讨论】:
-
我们能看到输出的样子吗?
-
@LucasDurand.. 请查看更新后的问题
-
@Data_is_Power 你可能不得不使用硒
-
@BittoBennichan.. 感谢您的及时回复!我们可以用 Python 做些什么?
-
是的。我尝试模拟 ajax 请求但不成功。我认为硒应该是这里的自然选择selenium-python.readthedocs.io
标签: python html pandas html-parser