我正在编写一个python爬虫程序,它可以在给定页面的urls中找到联系人链接。然而,我的if语句看起来很糟糕:
if 'news' not in link and 'archive' not in link and 'download' not in link and 'career' not in link and '././' not in link and '..' not in link and '../' not in link and 'store' not in link and 'mailto' not in link and 'tel:' not in link and '.pdf' not in link:必须有更好的方法来做到这一点。尤其是因为当我浏览越来越多的站点时,我会添加更多关于url可以包含什么的规则。
请帮帮我!
发布于 2020-05-15 13:27:45
发布于 2020-05-15 13:28:41
您可以聪明地使用all和列表理解
checks = ['foo', 'bar']
link = ['something']
if all(k not in link for k in checks):
#do something如果给定列表中的所有项都为True,则all返回True
如果给定列表中的任何项为True,则any返回True
示例:
>>> l0 = [False, False]
>>> any(l0)
False
>>> all(l0)
False
>>> l1 = [True, False]
>>> any(l1)
True
>>> all(l1)
False
>>> l2 = [True, True]
>>> any(l2)
True
>>> all(l2)
True发布于 2020-05-15 13:40:30
您可以使用列表来存储匹配模式,而不是在单个条件中检查所有匹配模式。例如。
link = 'https://example.com/news'
matchings = ['news', 'archive', 'etc']
for match in matchings:
if not match in link:
do_something()
breakhttps://stackoverflow.com/questions/61812278
复制相似问题