我从网页中提取数据,但希望将其排列到pandas dataframe表中
finviz = requests.get('https://finviz.com/screener.ashx?v=152&o=ticker&c=0,1,2,3,4,5,6,7,10,11,12,14,16,17,19,21,22,23,24,25,31,32,33,38,41,48,65,66,67&r=1')
finz = html.fromstring(finviz.content)
col = finz.xpath('//table/tr/td[@class="table-top"]/text()')
data = finz.xpath('//table/tr/td/a[@class="screener-link"]/text()')
Col是数据帧的列,数据列表中的28个数据点将相应地排列成行。第二行中的数据点29到56,以此类推。如何优雅地编写代码
datalist = []
for y in range (28):
datalist.append(data[y])
>>> datalist
['1', 'Agilent Technologies, Inc.', 'Healthcare', 'Medical Laboratories & Research', 'USA', '23.00B', '29.27', '4.39', '4.53', '18.76', '1.02%', '5.00%', '5.70%', '3
24.30M', '308.52M', '2.07', '8.30%', '15.70%', '14.60%', '1.09', '1,775,149', '2', 'Alcoa Corporation', 'Basic Materials', 'Aluminum', 'USA', '1.21B', '-']
但是结果不是像dataframe那样的表格形式
Pandas有一个解析HTML的函数:^{}
您可以尝试以下操作:
如果HTML页面结构发生变化,我可以让您改进数据选择!父
div id
可能有用解释“
[-2]
”:该read_html
返回数据帧列表:因此,为了获得所需的数据帧,我选择了结尾前的第二个元素
[-2]
。这个discussion解释了负索引相关问题 更多 >
编程相关推荐