【问题标题】:Incorrect output when downloading .html files下载 .html 文件时输出不正确
【发布时间】:2023-03-05 07:40:01
【问题描述】:

我只是想在 python 中下载 .html 文件。 代码:

import urllib2 
    hdr = {'User-Agent': 'Mozilla/5.0'}
    urls=['http://www.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211']
    path='C:/Users/sony/Desktop/Python'
    for i,site in enumerate(urls):
        print (site)
        req = urllib2.Request(site, headers=hdr)
        page = urllib2.build_opener(urllib2.HTTPCookieProcessor).open(req)
        page_content = page.read()
        with open(path+'/'+str(i)+'.html', 'w') as fid:
            fid.write(page_content)

但这有时会给出这个输出 https://drive.google.com/file/d/0B16PrXUjs69zWFJvWmJ6aFhyN0k/view?usp=sharing 我根本不明白。 我在 python 中使用 goose 读取了这个文件,当我读取这样的文件时没有显示任何内容。

当它不起作用时: http://www.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211

【问题讨论】:

  • @LutzHorn 请立即查看。抱歉之前没提过。

标签: python urllib2


【解决方案1】:

使用requests 为您完成所有工作,使用.content 让请求处理编码:

import requests

urls=['http://www.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211']

 path='C:/Users/sony/Desktop/Python'

for i,site in enumerate(urls):
    print (site)
    req = requests.get(site)
    page_content = req.content
    with open ('{}{}.html'.format(path,i), 'w') as fid:
        fid.write(page_content)

输出:

 <!DOCTYPE html> <!--NEW--> <!--- www pageHead.vm ---> <!--- mode=www ---> <!--- URI=/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211 ---> <!--- Host=www.nydailynews.com ---> <!--[if IE 8]><html class="ie8" lang="en" itemscope itemtype="http://schema.org/"><![endif]--> <!--[if IE 9]><html class="ie9" lang="en" itemscope itemtype="http://schema.org/"><![endif]--> <!--[if IE 10]><html class="ie10" lang="en" itemscope itemtype="http://schema.org/"><![endif]--> <!--[if IE 11]><html class="ie11" lang="en" itemscope itemtype="http://schema.org/"><![endif]--> <!--[if !IE]><!--> <html lang="en" itemscope itemtype="http://schema.org/"> <!--<![endif]-->       <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/>          <title>Fans stampede outside South African stadium - NY Daily News</title>     <meta name="nydn_section" content="Sports"/>   <meta name="viewport" content="width=1070, maximum-scale=1.0"/>  <meta property="fb:app_id" content="107464888913"/> <meta property="fb:admins" content="1594068001"/> <meta property="og:site_name" content="NY Daily News"/> <meta property="article:publisher" content="https://www.facebook.com/thenewyorkdailynews"/> <meta name="msvalidate.01" content="02916AAC0DA8B068EFE01D721E03ED7E"/>    <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@nydailynews"> <meta property="twitter:url" content="http://www.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211"/> <meta property="twitter:title" content="Fans stampede outside South African stadium"/> <meta property="twitter:description" content="Thousands of fans stampeded outside the stadium gates of a World Cup warmup game Sunday, five days before the start of soccer's showcase event. Several fans could be seen falling under the crush of people, many wearing Nigeria jerseys."/> <meta id="og_title" property="og:title" content="Fans stampede outside South African stadium"/> <meta property="og:type" content="article"/> <meta id="og_url" property="og:url" content="http://www.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211"/>   <meta id="og_image" property="og:image" content="http://assets.nydailynews.com/polopoly_fs/1.179213!/img/httpImage/image.jpg_gen/derivatives/landscape_1200/alg-stampede-johannesburg-jpg.jpg"/>   <meta id="og_description" property="og:description" content="Thousands of fans stampeded outside the stadium gates of a World Cup warmup game Sunday, five days before the start of soccer's showcase event. Several fans could be seen falling under the crush of people, many wearing Nigeria jerseys."/> <meta name="description" content="Thousands of fans stampeded outside the stadium gates of a World Cup warmup game Sunday, five days before the start of soccer's showcase event. Several fans could be seen falling under the crush of people, many wearing Nigeria jerseys."/>   <meta name="nydn_byline" content="MICHAEL LEWIS"/>   <link rel="stylesheet" type="text/css" href="http://assets.nydailynews.com/nydn/c/nydn.css?r=20120405mk1Bh">  <meta name="parsely-title" content="Fans stampede outside South African stadium"/> <meta name="parsely-link" content="http://www.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211"/> <meta name="parsely-type" content="article"/> <meta name="parsely-image-url" content="http://assets.nydailynews.com/polopoly_fs/1.179213!/img/httpImage/image.jpg_gen/derivatives/landscape_1200/alg-stampede-johannesburg-jpg.jpg"/>    <meta name="parsely-pub-date" content="2010-06-06T15:01:04"/>   <meta name="parsely-section" content="Sports"/>   <meta name="parsely-author" content="Michael Lewis"/>       <link rel="stylesheet" type="text/css" href="http://assets.nydailynews.com/nydn/c/article.css?r=20120405mk1Bh">       <meta name="robots" content="NOARCHIVE"/>         <link rel="canonical" href="http://www.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211">  <link rel="alternate" media="handheld" href="http://m.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211"> <link rel="alternate" media="only screen and (max-width: 640px)" href="http://m.nydailynews.com/sports/soccer-fans-stampede-south-african-stadium-nigeria-north-korea-world-cup-warmup-article-1.179211"/>     <script type="text/javascript" src="http://assets.nydailynews.com/nydn/js/nydn-pack-20140101.js?r=20120405mk1Bh"></script>   <script type="text/javascript" src="http://assets.nydailynews.com/nydn/js/article2014.js?r=20120405mk1Bh"></script>          <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->      


                              <link rel="alternate" type="application/rss+xml" title="NYDN Rss" href="http://feeds.nydailynews.com/nydnrss">              <link rel="alternate" type="application/rss+xml" title="Sports Rss" href="http://feeds.feedburner.com/nydnrss/sports">       

..........................

如果您想多次尝试相同的 url,您可以使用 try/except 捕获 requests.ConnectionError

def tries(path, url, i, max_tries=1):
    for ty in range(1, max_tries+1):
        try:
            req = requests.get(url)
            page_content = req.content
            with open('{}{}.html'.format(path, i), 'w') as fid:
                fid.write(page_content)
            break
        except requests.exceptions.ConnectionError as e:
            print("Error {} for try {}".format(e, ty))


for ind, url in enumerate(urls):
    tries(path, url, ind, 4)

【讨论】:

  • 由于工作在缓慢的互联网连接上,我面临一些超时问题stackoverflow.com/questions/30373301/…。你认为这也能解决这个问题吗?还是我应该在上面明确指定超时?
  • Cunninghan 你的代码有一些错误with open(path {}.html'.format(i), 'w') as fid: ^ SyntaxError: invalid syntax
  • 是的。错过了开场白。固定的。如果超时,您希望发生什么?
  • 立即尝试。用手机工作很难看清楚
  • 如果发生这种情况,你想继续尝试吗?
【解决方案2】:

从响应头来看:

>> print page.info()
Cache-Control: public, max-age=300, s-maxage=300
Content-Type: text/html;charset=utf-8
Server: fs3
Age: 103
Expires: Thu, 21 May 2015 13:36:40 GMT
Content-Encoding: gzip
Transfer-Encoding: chunked
Connection: close
Vary: Accept-encoding, Accept-Encoding

我看到内容是gzip压缩的,尝试使用zlib模块解压数据。

要检查数据是否已压缩,请添加以下行:

if page.info().get('Content-Encoding', '') == 'gzip':
    ... # decompress data

请阅读this 了解如何为身体减压的示例。

【讨论】:

  • @schelzz15 你建议什么解决方案?
  • @schelzz15 两点- 1. 因为我对很多网址都这样做,所以这种情况根本不存在。有什么可能的方法来检查它 2. 你能提供一个例子吗?
  • @AbhishekBhatia 我已经添加了一个 URL 来说明如何做到这一点。
  • 因为所有的都不在 gzip 中。我认为也应该进行检查。你能具体说明如何做到这一点吗?
  • 我认为 http 服务器不应该发送 gzip 编码的数据,除非客户端列出它们支持它(我不认为 urllib2 是开箱即用的)。
猜你喜欢
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 2021-01-14
  • 2014-06-07
  • 1970-01-01
  • 2011-03-12
相关资源
最近更新 更多