python - 如何过滤掉静态语料库中的爬虫陷阱
问题描述
我正在做一项作业,要求我们编写一个程序来抓取给定的静态语料库。在输出中,我的代码打印了所有爬网的 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
我想从我的结果中过滤掉那些,但我想不出任何办法。
解决方案
我认为这将解决您的问题
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!')
推荐阅读
- flutter - 如何根据 dart、Flutter 中订单的交货时间对元素列表进行排序?
- php - TCP 客户端套接字写入失败
- php - 我应该定义自己的 HTTP 响应代码以从 PHP 发送吗?
- angular - 使用@ngx-translate/core 同时翻译两个不同语言的字符串?
- python - 通过 win32com 使用 Outlook,突然出现运行时错误 '_Folders' object is not callable`
- java - 将字符串结果分配给未知大小的数组
- java - 在 Java 中解析时间戳
- kubernetes-helm - 在 helm 模板中查找 configmap 值
- selenium - 使用 puppeteer 的 wsEndpoint 自动连接 chrome 浏览器以重新连接到打开的窗口的安全问题
- python - 使用 ipaddress 模块从主列表中排除子网?