如何使用linkch忽略包含图片格式的URL

2024-06-16 11:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用linkchecker抓取英国政府网站,映射超链接之间的关系,并输出到GML文件。在

我不想包含图像的URL,例如任何包含jpeg或png文件格式引用的URL(例如www.gov.uk/somefile.jpeg"). 在

我已经尝试了几个小时来使用--ignore-url命令行参数和各种正则表达式来实现这一点。这是我放弃之前的最后一次尝试:

linkchecker --ignore-url='(png|jpg|jpeg|gif|tiff|bmp|svg|js)$' -r1 --verbose --no-warnings -ogml/utf_8 --file-output=gml/utf_8/www.gov.uk_RECURSION_1_LEVEL_NO_IMAGES.gml https://www.gov.uk

有谁能告诉我这是否可行,如果有,请提出解决办法?在


Tags: 文件url关系png网站wwwutfjpeg
1条回答
网友
1楼 · 发布于 2024-06-16 11:21:45

琐事:

根据docs

ignore-url=REGEX

URLs matching the given regular expression will be ignored and not checked.

This option can be given multiple times.

LinkChecker accepts Python regular expressions. See http://docs.python.org/howto/regex.html for an introduction. An addition is that a leading exclamation mark negates the regular expression.

因此,我们可以很容易地用python检查regex,看看它为什么不起作用(live test):

import re

our_pattern = re.compile(r'(png|jpg|jpeg|gif|tiff|bmp|svg|js)$')
input_data = '''
www.gov.uk/
www.gov.uk/index.html
www.gov.uk/admin.html
www.gov.uk/somefile.jpeg
www.gov.uk/anotherone.png
'''

input_data = input_data.strip().split('\n')

for address in input_data:
    print('Address: %s\t Matched as Image: %s' % (address, bool(our_pattern.match(address))))
    #                                                           ^ or our_pattern.fullmatch

输出:

^{pr2}$

我想,这里的问题是因为部分匹配,所以让我们试试完全匹配(patternlive test):

...
our_pattern = re.compile(r'.*(?:png|jpg|jpeg|gif|tiff|bmp|svg|js)$')
#                          ^ Note this (matches any character unlimited times)
...

…输出为:

Address: www.gov.uk/     Matched as Image: False
Address: www.gov.uk/index.html   Matched as Image: False
Address: www.gov.uk/admin.html   Matched as Image: False
Address: www.gov.uk/somefile.jpeg    Matched as Image: True
Address: www.gov.uk/anotherone.png   Matched as Image: True

解决方案:

如您所见,在您的尝试中,您的url与给定的正则表达式不匹配,因此不会被忽略。唯一与regex匹配的是列出的扩展名(png,jpg,…)。在

要解决此问题,请使用.*匹配扩展名之前的所有字符。 另一个问题是加引号。在

根据doc的例子:

Don't check mailto: URLs. All other links are checked as usual:

linkchecker ignore-url=^mailto: mysite.example.org

所以你最后的选择是:

 ignore-url=.*(?:png|jpg|jpeg|gif|tiff|bmp|svg|js)$

希望有帮助!在

相关问题 更多 >