我在python 2.7上创建自己的网络抓取工具,将网站下载到我的计算机中的路径,并保存文件的方式与保存在服务器上的网站文件夹中的方式相同,例如:
https://stackoverflow.com/questions/ask?title=python+how+to+change+links+of+html+file+to+local+links
我将在其中的stackoverflow目录中创建一个问题目录,并在其中包含此页面的html文件...
如何更改指向互联网页面的链接,以便链接到我下载的页面(如果它们已存在于我的计算机上)?
例如,如果有:
<a href="https://stackoverflow.com/questions">
所以我将通过python更改此html代码
<a href="/questions">
或类似的东西..
我不知道它是否有帮助,但这是我用来在单个文件上下载的功能: def downloadFile(path,url):
try :
print "Downloading : " + url
path=path + urlparse(url).path
path , fileName = pathNameSplit(path)
make_sure_path_exists(path)
print "trying to downoad " + fileName
if (fileName.count(".") == 0 ):fileName = fileName + ".html"
#pickle.dump( url2Html(url) , open( path + fileName, "w" ))
urllib.urlretrieve(url, path + fileName)
print "Download of " + url + " Completed"
except Exception:
print "Sometihng occured in the download of " + url
答案 0 :(得分:1)
每当您抓取链接并将页面保存到路径时,请将链接和路径保存到字典中。
你还需要确定一些事情 1.每个路径对于一个链接是唯一的(一种可选的,但我认为非常有用) 2.您没有从另一个链接覆盖该路径中的任何其他页面
然后,在完成爬网之后,您需要“手动”(当然,使用一些python代码)编辑下载文件中的链接,而不是指向文件系统上的文件。
通过手动编辑,我的意思是使用一些模块(re
)来搜索和替换下载文件中的字符串。
进行此转换后,您将失去对作为文件原始来源的网页的引用。
如果您需要保留原始在线网址,您可以简单地为每个网址指定一个唯一ID,并将其存储在您的本地数据库中(当然还有文件系统路径 - 您下载文件的地方).. < / p>
如果您不能自己动手,请寻求更多帮助。
<强> [编辑] 强> 使用 re 模块,您可以执行以下操作
import re
html_file_content = u"asdf 1234 this should contain the source code of a html page that you downloaded"
pattern = u"http://the-url-from-which-you-downloaded-the-html-file.com"
path = u"d:/whatever/path/where/you/downloaded/the/html/file"
new_file_content = re.sub(pattern, path, a)
名称new_file_content
将包含源文件,文件系统路径而不是链接...请确保将文件://连接到path
变量的开头,这样浏览器可以将其识别为有效链接(例如file://d:/downloads/python_crawler
,而不只是d:/downloads/python_crawler