gpt4 book ai didi

python - BeautifulSoup 没有按预期下载文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:27 25 4
gpt4 key购买 nike

我正在尝试从 this 下载所有 .txt 文件具有以下代码的网站:

from bs4 import BeautifulSoup as bs
import urllib
import urllib2

baseurl = "http://m-selig.ae.illinois.edu/props/volume-1/data/"

soup = bs(urllib2.urlopen(baseurl), 'lxml')
links = soup.findAll("a")
for link in links:
print link.text
urllib.urlretrieve(baseurl+link.text, link.text)

当我运行这段代码时,print(link.text) 行打印出正确的文件名并且目录中填充了具有正确名称的文件,但文件的内容看起来像:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /props/volume-1/data/ ance_8.5x6_2849cm_4000.txt was not found on this server.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>
<address>Apache/2.2.29 (Unix) mod_ssl/2.2.29 OpenSSL/1.0.1e-fips mod_bwlimited/1.4 Server at m-selig.ae.illinois.edu Port 80</address>
</body></html>

因此,我确定通信正常,但我没有正确指示 BS 如何保存文件内容。

此外,我目前正在使用 findAll("a") 命令下载所有文件,但实际上我只想下载名称为 *geom 的特定文件。文本文件

最佳答案

您正在阅读链接的文本,而不是 href,并且文本包含一个额外的空格。这将检索 hrefs:

links = soup.findAll("a", href=True)
for link in links:
print link['href']
urllib.urlretrieve(baseurl+link['href'], link['href'])

I would actually like to only download specific files with names such as *geom.txt

在循环中,您可以检查,例如,if "geom"in link['href']:

关于python - BeautifulSoup 没有按预期下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37531063/

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