首页 > 解决方案 > 如何返回导致包含 True 标志的关键字

问题描述

我的 Python 脚本的目的是在几个网站的 html 中查找几个不同的字符串,如果找到其中一个字符串,它将返回一个 True 标志。

代码:

import operator
import requests
import threading

# search for any of these items
search_for = ['about me', 'home page', 'website', 'submit your link', 'add a link']

# threads
threads = []

def send_get_request(link, search_for):
    try:
        html = requests.get(link)
    except requests.exceptions.RequestException as e:
        return False, e
    text = html.text.lower()
    if any(operator.contains(text, keyword.lower()) for keyword in search_for):
        return (True, link)
    else:
        return (False, link)


def process_result(result):
    if True in result:
        with open("potentialLinks.txt", "a") as file:
            file.write('{}\n'.format(str(result)))
            print("Success: {}".format(str(result)))
    else:
        print("Failed: {}".format(str(result)))


def main():
    # open and loop the links
    with open("profiles.txt", "r") as links:
        for link in links:
            link = link.strip()
            results = send_get_request(link, search_for)
            process_result(results)


# entry point ...
if __name__ == '__main__':
    main()

我遇到的问题是:

if any(operator.contains(text, keyword.lower()) for keyword in search_for): 

当它在 html 中找到一个关键字时,我是否可以返回它找到的哪个关键字导致 True 标志触发?

我想不出最好的方法来做到这一点,很可能我在想一些小事,谢谢你在这件事上的任何帮助。

标签: python

解决方案


found = None 
for keyword in ["apple" ,"cat"]:
     if keyword.lower() in "this is a cat and this is not":
          found = keyword
          break

如果您想要所有匹配的关键字,请使用

[keyword for keyword in ["apple" ,"cat"] if keyword.lower() in "this is a cat and this is not an apple"]

推荐阅读