python请求加载大页面解决方案

时间:2017-05-22 07:39:03

标签: python parsing url get python-requests

使用Python请求lib打开大约82,000行的大页面时遇到了这个问题。在我尝试使用urllib2之前,这里出现了错误" IncompleteRead"

现在有了请求:

 r = requests.get(https://www.bhphotovideo.com/c/search?atclk=Model+Year_2016&Ns=p_PRICE_2|0&ci=13223&ipp=120&N=4110474291+4294948825+3665082495)
 page_source = r.content
 print page_source

源打印的结果未满,我看到结束标记,但不是从文档的开头!

您有任何想法,如何加载此网址的完整内容? 82000行。

1 个答案:

答案 0 :(得分:2)

大多数(如果不是全部)shell都有字符限制。将page_source保存到文件中可确认requests.get返回整个页面:

import requests

r = requests.get('https://www.bhphotovideo.com/c/search?atclk=Model+Year_2016&Ns=p_PRICE_2|0&ci=13223&ipp=120&N=4110474291+4294948825+3665082495')
page_source = r.text
with open('test.txt', 'w') as f:
    f.write(page_source.strip())

文件内容以<!DOCTYPE html>开头,.text是页面的开头。 另请注意,我使用.content而不是.strip()来更清晰地表示页面源。我还使用了'\n',因为此页面的来源由于某种原因以无用的page_source开头。

另一种方法是简单地打印print(page_source[:100]) # <!DOCTYPE html> # <!--[if lt IE 7]> <html class="ie lt-ie7"> <![endif]--> # <!--[if IE 7]> 的前100个(或其他)字符:

{{1}}