【问题标题】:How to search multiple keywords in web page? this only input one keyword如何在网页中搜索多个关键字?这个只输入一个关键字
【发布时间】:2022-01-25 10:51:45
【问题描述】:

进口机械化 从 bs4 导入 BeautifulSoup 进口时间 导入smtplib

默认为真

当真时:

url = "https://www.google.com"
browser = mechanize.Browser()
browser.open(url)
response = browser.response().read()
soup = BeautifulSoup(response, "lxml")
count = 1
if str(soup).find("English") == -1:
    # wait 60 seconds (change the time(in seconds) as you wish),
    print('Checking - ' + str(count) + 'th Time')
    time.sleep(60)
    count += 1
    # continue with the script
    continue

【问题讨论】:

  • 这个只能搜索“英文”关键字我要添加更多关键字
  • 搜索多个词,如果该词出现在网站上我需要提醒

标签: python


【解决方案1】:

这里有几个问题:

  1. 美汤提供get_text()提取文本的方法,无需转成字符串。
  2. 当没有找到值时,字符串的find() 返回-1。你确定这是你想要的吗?
  3. 你为什么使用time.sleep()?停止程序的目的是什么?
  4. 您没有创建循环,这会使count 变得多余,并且您将收到continue 的错误。
  5. 如果你想得到一个字符串出现的次数,你可以使用regex's findall()然后得到它的长度,比如:len(re.findall("English", soup_text))。
  6. 如果要查找多个关键字,可以创建一个关键字列表,然后像这样循环遍历它们:
    for k in ["a", "b", "c"]:
        print(f'{k}: {len(re.findall(k, soup.get_text()))}')
    

完整示例:

from bs4 import BeautifulSoup
import requests  # simple http request
import re  # regex

url = "https://www.google.com"
doc = requests.get(url)
soup = BeautifulSoup(doc.text, "lxml")
soup_text = soup.get_text()
keywords = ["Google", "English", "a"]
for k in keywords:
    print(f'{k}: {len(re.findall(k, soup_text))}')

强烈建议你彻底学习python:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多