【问题标题】:Python BeautifulSoup check outputPython BeautifulSoup 检查输出
【发布时间】:2017-05-28 12:02:41
【问题描述】:

我尝试检查网站打印的内容。 想象一下:

page = requests.get("testsite.com")
soup = BeautifulSoup(page.content)
if soup in ["my", "wished", "output"]:
    print "It's there!"
else:
    print "It's not there!"

所以我想检查网站是否包含文本“我的”、“希望的”或“输出”。我该怎么做?

谢谢!

【问题讨论】:

  • 你在检查什么?你的例子没有意义。
  • 我知道。正因为如此,我在这里。我想检查网站是否包含文本“我的”、“希望的”或“输出”

标签: python urllib webrequest bs4


【解决方案1】:

您可以使用map 函数并在page 中查找字符串。如果page 中没有想要的字符串,则返回的列表将仅包含-1(即[-1, -1, -1])。因此,只需检查是否有大于-1 的数字。

page = requests.get("testsite.com")
page = page.text
wanted = ["my", "wished", "output"]
if max(map(page.find, wanted)) > -1:
    print "It's there!"
else:
    print "It's not there!"

【讨论】:

    【解决方案2】:
    page = requests.get("testsite.com")
    test = ["my", "wished", "output"]
    if any(t in page.text for t in test):
        print("It's there!")
    else:
        print("It's not there!")
    

    soup是BeautifulSoup对象,如果你想检查字符串中的文本,你应该使用string object,比如page.text

    any(iterable) 如果可迭代的任何元素为真,则返回真。如果 可迭代对象为空,返回 False。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      相关资源
      最近更新 更多