python—当I';我正试图从网站上获取文档

python—当I';我正试图从网站上获取文档,python,beautifulsoup,Python,Beautifulsoup,我试图从这个页面下载文档 我试图下载页面上的25个文档。 我认为这很简单,下面是我的代码: from BeautifulSoup import BeautifulSoup import re import urllib2 import os if __name__ == "__main__": pre_url = "http://securities.stanford.edu" url = "http://securities.stanford.edu/fmi/xsl/SCACPUD

我试图从这个页面下载文档

我试图下载页面上的25个文档。 我认为这很简单,下面是我的代码:

from BeautifulSoup import BeautifulSoup
import re
import urllib2
import os

if __name__ == "__main__":
  pre_url = "http://securities.stanford.edu"
  url = "http://securities.stanford.edu/fmi/xsl/SCACPUDB/recordlist.xsl?-db=SCACPUDB&-lay=Search&FIC_DateFiled_Quater=Q1&FIC_DateFiled_Year=2011&-sortfield.1=FIC_DateFiled&-sortfield.2=LitigationName&-sortorder.1=ascend&-max=25&-find" 
  response = urllib2.urlopen(url)
  soup = BeautifulSoup(response.read()).findAll('tr')
  url_list = []
  for s in soup[8:]:
    url_list.append(pre_url + s.a['href'])
  for x in url_list:
    name = x.split("/")[4]  
    context = urllib2.urlopen(x).read()
    soup = BeautifulSoup(context)
    file = open(name + ".txt", "w")
    file.write(soup.prettify())
  print "DONE"
执行脚本后,我成功下载了25个文件。 但后来我发现其中10个都是垃圾角色! 怎么会? 有人能帮我吗

非常感谢,我很抱歉我的英语不好

更新: 这是脚本可能会错误下载的页面之一

您的问题可能是以文本模式打开文件,但它们是以二进制模式下载的。将上述表达式替换为

open(name + ".txt", "wb")

看看它是否能改善情况。

示例页面是用UTF-16编码的,没有在页眉中正确提供factoid

>>> page = urllib2.urlopen( "http://securities.stanford.edu/1046/BWEN00_01" )
>>> page.info().headers
['Date: Mon, 22 Aug 2011 13:13:56 GMT\r\n', 'Server: Apache/1.3.33 (Darwin) mod_jk/1.2.2 DAV/1.0.3\r\n', 'Cache-Control: max-age=60\r\n', 'Expires: Mon, 22 Aug 2011 13:14:56 GMT\r\n', 'Last-Modified: Thu, 21 Jul 2011 22:06:51 GMT\r\n', 'ETag: "18b9a6e-9af6-4e28a2fb"\r\n', 'Accept-Ranges: bytes\r\n', 'Content-Length: 39670\r\n', 'Connection: close\r\n', 'Content-Type: text/html\r\n']

尝试
page.decode('utf-16')
以正确的Unicode字符而不是字节查看页面。

“垃圾字符”具有误导性。提供实际例子。如果您使用了错误的工具,您的文件中满是Unicode,当它实际上只是UTF-16 Unicode时,它将不会显示为“垃圾”。垃圾字符如下所示:䠼䵔㹌䠼䅅㹄吼呉䕌䴾湡歮湩⁤潃灲牯瑡潩ⴠ匠捥牵瑩敩⁳汃獡⁳†捁楴湯⼼䥔䱔㹅ഠ㰍䕍䅔丠䵁㵅䐧卅剃偉䥔乏‧佃呎久㵔㰧㹢畓浭牡㩹⼼㹢䄠捣牯楤杮琠⁡牰獥⁳敲敬獡⁥慤整⁤敆牢慵祲㈠‬〲ㄱ‬慍湮楋摮椠⁳⁡楢灯慨浲捡略楴慣潣灭湡⁹潦畣敳⁤湯琠敨搠獩潣敶祲‬敤敶潬浰湥⁴湡⁤潣浭牥楣污穩瑡潩景琠敨慲数瑵捩瀠潲畤瑣⁳潦⁲楤敳獡獥‬畳档愠⁳楤扡这没有多大帮助-您需要使用“垃圾”字符的
repr()
更新问题。您还需要包括页面附带的标题,因为标题提供了语言,最重要的是提供了编码信息。您能否提供一个示例,说明您可以自己(使用浏览器)正确下载但程序错误下载的页面?请在您拥有该问题时更新该问题。请不要在自己的问题中添加评论。请使问题完整一致。
>>> page = urllib2.urlopen( "http://securities.stanford.edu/1046/BWEN00_01" )
>>> page.info().headers
['Date: Mon, 22 Aug 2011 13:13:56 GMT\r\n', 'Server: Apache/1.3.33 (Darwin) mod_jk/1.2.2 DAV/1.0.3\r\n', 'Cache-Control: max-age=60\r\n', 'Expires: Mon, 22 Aug 2011 13:14:56 GMT\r\n', 'Last-Modified: Thu, 21 Jul 2011 22:06:51 GMT\r\n', 'ETag: "18b9a6e-9af6-4e28a2fb"\r\n', 'Accept-Ranges: bytes\r\n', 'Content-Length: 39670\r\n', 'Connection: close\r\n', 'Content-Type: text/html\r\n']