[英]How to output the python print result into a table or CSV format?
我是 Python 新手,现在我正在尝试学习网络抓取以进行个人旅行计划。 我想知道打印结果后,如何将其输出为表格格式或CSV格式。
现在结果如下:
{'price': '115', 'name': 'The hotel name'}
{'price': '97', 'name': 'the hotel name'}
.......
我谷歌了一些模块的方法,比如pandas和prettytable,发现这对我来说太难理解了。 所以我来这里看看是否有任何解决方案可以解决我的问题。
代码如下:
import requests
from bs4 import BeautifulSoup
url="http://hotelname.com/arrivalDate=05%2F23%2F2016**&departureDate=05%2F24%2F2016" #means arrive on May23 and leaves on May
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text,'lxml')
names = soup.select('.PropertyName')
prices = soup.select('.RateSection ')
for name,price in zip(names,prices):
data = {
"name":name.get_text(),
"price":price.get_text()
}
print (data)`
我希望你以前的代码是正确的,写作部分;
import csv
with open('filename.csv', 'w') as csvfile: #create csv file with w mode
fieldnames = ['names', 'prices'] #header names
writer = csv.DictWriter(csvfile, fieldnames=fiel dnames) #set the writer
writer.writeheader()
for name,price in zip(names,prices): #writing the elements
writer.writerow({'names': name.get_text(), 'prices': price.get_text()})
您可以使用 Pandas 创建一个 DataFrame,然后将 DataFrame 写入 csv。 这将需要对您的 dict 稍作更改以使其更容易,代码可能如下所示:
import pandas as pd
#...
data = {
0: {"name": name.get_text()},
1: {"price": price.get_text()}
}
df = pd.DataFrame.from_dict(data, orient='index')
df.to_csv('filename.csv', index=False)
您只需要写入要打印值的文件:
import requests
import csv
from bs4 import BeautifulSoup
url="http://hotelname.com/arrivalDate=05%2F23%2F2016**&departureDate=05%2F24%2F2016" #means arrive on May23 and leaves on May
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text,'lxml')
names = soup.select('.PropertyName')
prices = soup.select('.RateSection ')
with open('results.csv', 'w') as outfile:
writer = csv.writer(outfile, delimiter=',')
writer.writerow(['Name', 'Price']]
for name,price in zip(names,prices):
writer.writerow([name.get_text(), price.get_text()])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.