簡體   English   中英

如何在 BeautifulSoup 對象中搜索字符串?

[英]How do you search for a string in a BeautifulSoup object?

我正在檢查 Craigslist 的帖子,看看它們是否已被標記為刪除。 我的腳本非常簡單:

import requests
from bs4 import BeautifulSoup

def check_if_flagged(url):
    page = requests.get (url)
    soup = BeautifulSoup(page.content, 'html.parser')
    return ('flagged for removal' in soup)

問題是,我有一個 url,我知道一個事實已被標記為刪除,但check_if_flagged返回False 這是在 BeautifulSoup 對象中搜索子字符串的正確方法嗎? 有沒有更優化的方法? 如果您重現此錯誤,請告訴我。

這是供參考的網址:'https://newyork.craigslist.org/brk/apa/d/brooklyn-1-bedroom-1-bath-apt-located/7206865558.html'

要搜索湯中的文本,您可以使用text=屬性。 或者您可以將返回的 HTML 代碼搜索為字符串:

import requests
from bs4 import BeautifulSoup

def check_if_flagged(url):
    page = requests.get(url).text
    return 'this posting has been flagged for removal' in page.lower()

def check_if_flagged2(url):
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    return bool(soup.find(text=lambda t: 'this posting has been flagged for removal' in t.lower()))

url = 'https://newyork.craigslist.org/brk/apa/d/brooklyn-1-bedroom-1-bath-apt-located/7206865558.html'
print(check_if_flagged(url))
print(check_if_flagged2(url))

印刷:

True
True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM