【发布时间】:2021-04-25 20:23:09
【问题描述】:
我知道这是一个相当普遍的问题,但是这种情况使它变得令人困惑。
我正在使用beautifulsoup 从网站上抓取某些数据,我也在使用它来检查我当前正在抓取的页面上的“下一页”链接,看看我是否可以抓取另一个。
next_page_button_finder = soup.find('ul', class_='navnext').text
为了检查结果如何,我使用以下方法打印它:
print(next_page_button_finder)
输出是:
Next >>
然而,这是奇怪的部分,当我尝试通过创建简单的 if 语句来验证这一点时:
if next_page_button_finder == "Next >>":
print("yes")
else:
print("no")
“no”被打印出来。
任何帮助将不胜感激。
这是您可以用来复制问题的代码(spareroom.com 的任何链接都可以使用,但是,为方便起见,您可以使用此链接https://www.spareroom.co.uk/flatshare/?search_id=1034984872&):
from bs4 import BeautifulSoup
import requests
html_address = input("Paste page the address here:")
html_text = requests.get(html_address).text
soup = BeautifulSoup(html_text, 'lxml')
prices = soup.find_all('strong', class_='listingPrice')
next_page_button_finder = soup.find('ul', class_='navnext').text
print(next_page_button_finder)
if next_page_button_finder == "Next >>":
print("yes")
else:
print("no")
【问题讨论】:
-
我的猜测是您可能在某处遗漏了一个空格,您可以尝试使用
list(next_page_button_finder)并打印出来 -
那里有更多字符,如果您在打印中输入 *,您会看到。现在你可以去掉额外的东西了。试试这个
print("*",next_page_button_finder,"*") if next_page_button_finder.strip() == "Next >>":
标签: python string if-statement beautifulsoup