python字符串垂直输出加循环_将漂亮的soup嵌套循环垂直输出到datafram中
我如何將這個web抓取(數(shù)據(jù))的輸出放入pandas數(shù)據(jù)幀?
下面的代碼只顯示一行數(shù)據(jù),并且是垂直排列的。如何使數(shù)據(jù)幀看起來完全像打印(數(shù)據(jù))-即水平?
另外,我是個新手,這可不是Python。請建議如何使其成為函數(shù)(?)?
我嘗試了所有類型的append和concat函數(shù),但是嵌套循環(huán)會使一切都陷入錯誤。請幫忙。
提前謝謝你。在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§ionId=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
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的python字符串垂直输出加循环_将漂亮的soup嵌套循环垂直输出到datafram中的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 什么是苹果耳塞?
 - 下一篇: python公共变量_Python中的公