【问题标题】:How to use beautifulsoup to check if a string exists如何使用 beautifulsoup 检查字符串是否存在
【发布时间】:2019-04-07 14:14:21
【问题描述】:

嗨,我正在尝试编写一个抓取 URL 的程序,如果抓取的数据包含特定的字符串,我该如何使用美丽的汤来实现这一目标

import requests
from bs4 import BeautifulSoup
data = requests.get('https://www.google.com',verify=False)
soup= BeautifulSoup(data.string,'html.parser')
for inp in soup.find_all('input'):
    if inp == "Google Search":
        print ("found")
    else:
        print ("nothing")

【问题讨论】:

  • 也许if "Google Search" in inp: ?

标签: python python-3.x beautifulsoup


【解决方案1】:

你的 inp 是一个 html 对象。您必须使用 get_text() 函数

import requests
from bs4 import BeautifulSoup
data = requests.get('https://www.google.com',verify=False)
soup= BeautifulSoup(data.string,'html.parser')
for inp in soup.find_all('input'):
    if inp.get_text() == "Google Search":
        print ("found")
    else:
        print ("nothing")

【讨论】:

    【解决方案2】:

    verify = False,禁用证书验证。这是一个安全问题。特别是如果您在公司网络内,这很危险,因为它为中间人攻击打开了可能性。您应该使用适当的证书授权。

    【讨论】:

    • 欢迎来到 SO @MLAlex。请您解释一下为什么没有在您的答案中使用它。
    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2011-07-30
    • 1970-01-01
    • 2023-03-28
    • 2018-08-07
    相关资源
    最近更新 更多