首页 > 解决方案 > 如何过滤掉静态语料库中的爬虫陷阱

问题描述

我正在做一项作业,要求我们编写一个程序来抓取给定的静态语料库。在输出中,我的代码打印了所有爬网的 URL,但我知道有些是陷阱,但我想不出一种方法来以 Python 的方式过滤掉它们。

我使用正则表达式过滤掉类似点击的 url 内容,但这在作业中是不允许的,因为它被认为是硬编码。

https://cbcl.ics.uci.edu/doku.php/software/arem?do=login§ok=4d26fc0839d47d4ec13c5461c1ed6d96

http://cbcl.ics.uci.edu/doku.php/software/arem?do=login§ok=d8b984cc6aa00bd1ef20471ac5150094

https://cbcl.ics.uci.edu/doku.php/software/arem?do=login§ok=d8b984cc6aa00bd1ef20471ac5150094

http://cbcl.ics.uci.edu/doku.php/software/arem?do=login§ok=d504a3676483838e82f07064ca3e12ee

和更多具有类似结构的。也有类似结构的日历 url,只是更改日期:

http://calendar.ics.uci.edu/calendar.php?type=day&calendar=1&category=&day=22&month=01&year=2017

http://calendar.ics.uci.edu/calendar.php?type=day&calendar=1&category=&day=25&month=01&year=2017

http://calendar.ics.uci.edu/calendar.php?type=day&calendar=1&category=&day=26&month=01&year=2017

http://calendar.ics.uci.edu/calendar.php?type=day&calendar=1&category=&day=27&month=01&year=2017

我想从我的结果中过滤掉那些,但我想不出任何办法。

标签: pythonpython-3.x

解决方案


我认为这将解决您的问题

    import requests

    for url in urls:
        try:
            response = requests.get(url)
            # If the response was successful, no Exception will be raised
            response.raise_for_status()
        except Exception as err:
            print(f'Other error occurred: {err}')
        else:
            print('Url is valid!')

推荐阅读