我是一名初学者,刚刚学习 Python,但决定暂时休息一下,探索一些库和脚本。我很快就确定 Python 可能非常适合自动搜索新住处。无论如何,该脚本将漂亮的 HTML 写入标准输出,但我正在努力写入文件,以便我可以在浏览器中查看输出。
代码如下:
#!/usr/bin/python
import requests
import pandas as pd
from bs4 import BeautifulSoup as bs4
url_base = 'http://eugene.craigslist.org/search/apa'
params = dict(bedrooms=2, housing_type=6)
rsp = requests.get(url_base, params=params)
print(rsp.url)
print(rsp.text[:500])
html = bs4(rsp.text, 'html.parser')
print(html.prettify()[:1000])
dwellings = html.find_all('p', attrs={'class': 'row'})
print(len(dwellings))
this_dwelling = dwellings[15]
print(this_dwelling.prettify())
我已经看过这个,但不清楚我具体在 write() 中放入什么内容来将脚本输出写入文件。
f = open('house.html','w')
f.write('What goes here?')
f.close()
然后我尝试了文件重定向和管道到 tee,返回此错误:
回溯(最近一次调用最后一次): 文件“./house.py”,第 10 行,位于 打印(rsp.text[:500]) UnicodeEncodeError:“ascii”编解码器无法对位置 0 处的字符 u'\ufeff' 进行编码:序数不在范围内(128)
也许我应该继续进行介绍性的 Hello World 练习并继续学习顺序,但现在我很沮丧,想先让这个脚本运行起来。总的来说,使用 Python 非常有趣。
最佳答案
尝试将住宅写入文件,而不是像这样将其打印到屏幕上。
f = open('house.html','w')
f.write(this_dwelling.prettify())
f.close()
将其放在脚本末尾,以使用一些结果填充 HTML 文件。
关于python - 将脚本的输出写入文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233317/