gpt4 book ai didi

python - 尝试从 nytimes.com 下载 .pdf .png 和 .jpg

转载 作者:行者123 更新时间:2023-11-28 19:20:10 24 4
gpt4 key购买 nike

我编写了一个简单的 Python 抓取工具来从 nytimes.com 的特定页面抓取一些文档。它可以正常工作,因为它可以抓取并正确格式化所有 URL,并尝试下载文件,并正确格式化名称。

但我得到的只是 1kb 的文件。我不知道为什么。这是我的代码:

import urllib2 
import urllib
from cookielib import CookieJar

files = 'http://www.nytimes.com/interactive/2014/11/25/us/evidence-released-in-michael-brown-case.html?_r=0'
slashpos = 0

def getLinks(url):
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
p = opener.open(url)
result = []
for line in p:
for element in line.split():
if element.startswith('href="http://gr'):
if element.endswith('pdf"') or element.endswith('png"') or element.endswith('jpg"'):
result.append(element[6:])
else:
continue
for char in result:
slashpos = char.rfind('/') + 1
urllib.urlretrieve(char, char[slashpos:-1])

getLinks(files)

感谢任何帮助。谢谢!

最佳答案

1) 使用 result.append(element[6:-1]) 而不是 result.append(element[6:]) (避免在url,下载失败的原因)
2) 保存文件使用 urllib.urlretrieve(char, char[slashpos:]) 而不是 urllib.urlretrieve(char, char[slashpos:-1])

关于python - 尝试从 nytimes.com 下载 .pdf .png 和 .jpg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27198862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com