使用python从网站页面中查找特定单词


theurl = "https://www.facebook.com/bbcnews"
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage,"html.parser")
body_elem = soup.findAll('div',{"class":"_1xnd"})
for word in body_elem:
c= word.text
if c == "BBC":
print(c)
else:
print("unable to find the element")

我想从页面中找到一个特定的单词,所以为了缩小搜索范围,我用"class"_1xnd"找到了"div",然后找到在该"div"中找到的所有文本,然后将给定的单词(在我的情况下是"BBC"(与在body.elem中找到的单词匹配。然后打印出"BBC",但它没有得到"BBC"这个词,而是打印出"else"部分。

进行c == "BBC"比较,检查c是否完全等于"BBC",但显然不是。c是全文。相反,请尝试:if "BBC" in c:,它有效。"BBC" in c检查字符串c.中是否出现"BBC">

最新更新