作者mhsu2k9 (mhsu2k9)
看板Python
标题[问题] Python写入文字档的问题
时间Thu Jan 19 16:17:08 2012
我最近为了跨平台使用,使用Python2写一支小程式
里面有一部份是要抓 html里面的 css tag,如果有找到css tag,就再去抓该css的地址
并读取其文字内容,再写回html档案,只是这样写回去,我再用文字编辑器打开看,
写回的css每一行之间都会再 "多空一行",虽然使用上无差别,但是还是有点恼人
请各位先进提点
谢谢
code 大致如下
#把网页内容读入htmlSource
urlItem = urllib2.urlopen("
http://xxx/xx.html)
htmlSource = urlItem.read()
urlItem.close()
#取得css位置的css文字档,并取代原有的css tag
regex = re.compile("(<link href=[\'\"]?([^\'\"]*)[\'\"]?[^>]*>)")
match = regex.findall(htmlSource);
for m in match:
cssTag = m[0]
cssLocation = m[1]
cssText = urllib2.urlopen(cssLocation).read()
htmlSource = htmlSource.replace(cssTag, "<style>" + cssText +
"</style>")
#写入档案
fileName = outputLocation
FILE = open(fileName,"w")
FILE.write(codecs.BOM_UTF8)
FILE.write(htmlSource)
FILE.close()
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 60.248.90.133
1F:→ apua:有可能该CSS文档的换行为'\r\n',而被编辑器视为两次换行 01/19 18:28
2F:→ apua:可以用 print repr(cssText) 检查看看换行的部分 01/19 18:29
3F:→ mhsu2k9:用binary mode开启新档就解决了 04/03 04:11
4F:→ mhsu2k9:FILE=open(fileName,"w") 改成 FILE=open(fileName,"wb") 04/03 04:12