如何解析特定单词的 BeautifulSoup 结果以定义布尔值?
How to parse BeautifulSoup results for a specific word to define a boolean?
我正在尝试获取 BeautifulSoup
结果并将它们解析为一个特定的词,我将定义某个值是 True
还是 False
。例如,如果我用 BeautifulSoup
解析特定的 id
元素并且它包含单词“yes”,那么 bool1 = True
。如果特定 id
元素包含单词“no”,则 bool1 = false
.
这是我目前拥有的:
from bs4 import BeautifulSoup, SoupStrainer
import requests
parse_only = SoupStrainer('h1')
page1 = requests.get('http://www.play-hookey.com/htmltest/')
soup = BeautifulSoup(page1.content, 'html.parser', parse_only=parse_only)
results1 = soup.find_all('h1')
print(results1)
然后我尝试解析 results1
以获取特定单词,如果它包含该单词,则布尔值将是 True
或 False
。
您可以搜索您想要的词是否在 results1
对象的 .text()
中:
import requests
from bs4 import BeautifulSoup
URL = "http://www.play-hookey.com/htmltest/"
soup = BeautifulSoup(requests.get(URL).content, "html.parser")
results1 = soup.find_all("h1")
# This will return True if found a match else False
print(any("WORD I'M LOOKING FOR" in tag.text.split() for tag in results1))
我正在尝试获取 BeautifulSoup
结果并将它们解析为一个特定的词,我将定义某个值是 True
还是 False
。例如,如果我用 BeautifulSoup
解析特定的 id
元素并且它包含单词“yes”,那么 bool1 = True
。如果特定 id
元素包含单词“no”,则 bool1 = false
.
这是我目前拥有的:
from bs4 import BeautifulSoup, SoupStrainer
import requests
parse_only = SoupStrainer('h1')
page1 = requests.get('http://www.play-hookey.com/htmltest/')
soup = BeautifulSoup(page1.content, 'html.parser', parse_only=parse_only)
results1 = soup.find_all('h1')
print(results1)
然后我尝试解析 results1
以获取特定单词,如果它包含该单词,则布尔值将是 True
或 False
。
您可以搜索您想要的词是否在 results1
对象的 .text()
中:
import requests
from bs4 import BeautifulSoup
URL = "http://www.play-hookey.com/htmltest/"
soup = BeautifulSoup(requests.get(URL).content, "html.parser")
results1 = soup.find_all("h1")
# This will return True if found a match else False
print(any("WORD I'M LOOKING FOR" in tag.text.split() for tag in results1))