python字符串垂直输出加循环_将漂亮的soup嵌套循环垂直输出到datafram中

我如何将这个web抓取(数据)的输出放入pandas数据帧?

下面的代码只显示一行数据,并且是垂直排列的。如何使数据帧看起来完全像打印(数据)-即水平?

另外,我是个新手,这可不是Python。请建议如何使其成为函数(?)?

我尝试了所有类型的append和concat函数,但是嵌套循环会使一切都陷入错误。请帮忙。

提前谢谢你。在from bs4 import BeautifulSoup as bs

import urllib.request

import re

import pandas as pd

Url1 = 'http://www5.statcan.gc.ca/cimt-cicm/topNCountryCommodities-marchandises?lang=eng&chapterId=27&sectionId=0&refMonth='

Url2 = '&refYr='

Url3 = '&freq=6&countryId=999&usaState=0&provId=1&arrayId=9900000&commodityId=271111&commodityName=Natural+gas%2C+liquefied&topNDefault=10&tradeType=3'

regexQ = re.compile('Date1 Qty')

regexC = re.compile('Footnote')

regexV = re.compile('Date1 Val')

import csv

import collections

for year in range(2016, 2018):

for month in range(0, 13):

sauce = urllib.request.urlopen(Url1+str(month)+Url2+str(year)+Url3).read().decode('utf-8')

soup = bs(sauce, 'lxml')

select = soup.find_all('option', selected=True)

for i in select:

Month=select[4]

Year=select[3]

month=Month.text

year=Year.text

#print(year)

#print(month, year)

value = [x.text.strip() for x in soup.find_all("td", {"headers": regexV})]

country = [x.text.strip() for x in soup.find_all("a", {"href": regexC})]

quantity = [x.text.strip() for x in soup.find_all("td", {"headers": regexQ})]

total_list = [list(x) for x in zip(country,quantity,value)]

for item in total_list:

h=[year , month]

data = h + item

print(data)

df = pd.DataFrame(data=data)

df.head

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值