python - if 语句不适用于抓取的网页文本

标签 python string if-statement beautifulsoup

我知道这是一个相当普遍的问题,但这种情况使它成为一个令人困惑的问题。

我正在使用 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")

最佳答案

What debugging shows

如果调试并停在 if 语句处,您会看到文本前后实际上包含换行符。您可以使用该字符串,或者简单地使用 string.strip()

预先剥离您的字符串

关于python - if 语句不适用于抓取的网页文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67257932/

相关文章:

python - 在 python 中快速查找

java - Android 将整数转换为字符串以及字符串转换为整数

c - 为什么我的代码取消了这部分代码的注释

java - if 语句可以嵌套在 while 循环中吗?

python - ValueError : Shapes (16, ) 和 (1, 16) 在 tensorflow1.0 中不兼容

Python 类实例具有唯一的某些属性

Python findall 字符串

javascript - 警报声明不起作用

java - boolean If 语句仅返回外部

python - Django - 信号。简单的例子开始