python - 如何返回导致包含 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 标志触发?
我想不出最好的方法来做到这一点,很可能我在想一些小事,谢谢你在这件事上的任何帮助。
解决方案
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"]
推荐阅读
- flutter - 如何使用下拉按钮显示通过 API (GET) 提取的数据
- c# - C# ssh 连接到 HP 交换机(绕过“更多”)
- powershell - 如何编写 Powershell 逻辑以从包含不同字符的行中提取特定字段
- node.js - 如何使用mongoDb获取字符串中关键字的出现次数
- javascript - 带有嵌套 td 子项的嵌套表,没有 Json 的标头
- python - Python。函数内部名称未定义错误
- java - 无法使用 Spring 反应式将消息作为字符串发送 - Webclient
- javascript - 如何在javascript中删除数组内的空对象
- android - 设置后如何删除 Image 组件的 tintColor ?
- node.js - (this.internalValue || []).findIndex 不是在 v-select 上启用多选时的函数