测试书签中的URL是否脱机或在python中联机

问题描述 投票:1回答:1

我想知道是否可以测试书签中的URL。所以我可以看到URL是否仍然在线或离线。

我可以看到我可以用Urllip2 Urllip2 code测试它

import socket
from urllib2 import urlopen, URLError, HTTPError

socket.setdefaulttimeout( 23 )  # timeout in seconds

url = 'http://google.com/'
try :
    response = urlopen( url )
except HTTPError, e:
    print 'The server couldn\'t fulfill the request. Reason:', str(e.code)
except URLError, e:
    print 'We failed to reach a server. Reason:', str(e.reason)
else :
    html = response.read()
    print 'got response!'
    # do something, turn the light on/off or whatever

我的问题是,我是否可以从我的书签(Chrome)获取链接/网址,并在网络中脱机或在线时测试网址(for)。

编辑26/02/2019 ...已经删除了这段代码,并且没有找到文件夹错误.. / import json from jsonpath_rw import parse import os

# PArse te Bookmarks file from json into a dict
input_filename = os.path.join(os.getenv("APPDATA"), "\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks")
if os.path.isfile(input_filename):
    with open(input_filename) as data_file:
        bookmark_data = json.load(data_file)

# Set an xpath expression for all 'url' children
    expr = parse('$..url')

# print the value of all url keys
    print([x.value for x in expr.find(bookmark_data)])
else:
    print("File not found!")
    print(input_filename)
python python-3.x google-chrome for-loop bookmarks
1个回答
0
投票

Chrome(或至少Chromium)将您的书签存储在Chrome配置区域中名为Bookmarks的文件中 - 在Linux上,这通常是Windows上的.config/chromium/Default/Bookmarks,它是AppData\Local\Google\Chrome\User Data\Default\Bookmarks(尽管如果您的系统不同,您可能需要寻找它)。

假设你要检查所有链接,那么你可能想要递归地遍历树,寻找url密钥并获取它们的值。由于这是JSON,我建议使用JSONPath库(https://readthedocs.org/projects/jsonpath-rw/),而不是编写自己的递归函数:

import json
from jsonpath_rw import parse

# PArse te Bookmarks file from json into a dict
with open('Bookmarks') as bm:
    data = json.load(bm)

# Set an xpath expression for all 'url' children
expr = parse('$..url')

# print the value of all url keys
print([x.value for x in expr.find(data)])
© www.soinside.com 2019 - 2024. All rights reserved.