【问题标题】:Beautiful Soup .get_text() does not equal Python string when it shouldBeautiful Soup .get_text() 应该不等于 Python 字符串
【发布时间】:2017-06-29 11:49:22
【问题描述】:

我正在使用 Beautiful Soup 从 html 元素中获取文本。

然后我使用循环和 if 语句将该文本与单词列表进行比较。如果它们匹配,我想返回确认。

然而,代码并没有确认任何匹配,即使打印语句显示实际上存在匹配。

def findText():
    text = ""

    url = 'www.site.com'


    #Get url and store
    page = requests.get(url)
    #Get page content
    soup = BeautifulSoup(page.content,"html.parser")

    els = soup.select(".className")

    lists = els[1].select(".className2")
            for l in lists:
                try:
                    text=l.find("li").get_text()
                except(AttributeError):
                    text="null"
    return text

def isMatch(text):
    #Open csv file
    listFile = open('list.csv', 'rb')
    #prep file to be read
    newListFile =csv.reader(listFile)


    match = ""
    for r in newListFile:
        if r[0]==text.lower():
            match = True
        else:
            match = False

    return match

    congressCSVFile.close()

匹配在输出中总是 False

print(r[0]) 在终端返回(比如说)“cat”

print(text) 在终端也返回“cat”

【问题讨论】:

    标签: python csv beautifulsoup


    【解决方案1】:

    您的循环是问题所在,或者至少是其中之一。一旦找到匹配的记录,您继续match 只会在 最后一条记录 匹配的情况下以 True 结束。要解决此问题,只需在找到匹配项时 return

    for r in newListFile:
        if r[0]==text.lower():
            return True
    return False
    

    不需要match 变量。

    更好的是,使用any() 函数:

    return any(r[0] == text.lower() for r in newListFile)
    

    【讨论】:

    • 谢谢,我不敢相信我错过了。但是,代码仍然无法工作/产生匹配。此外,在写这篇文章之前,我尝试在循环中有匹配项时打印确认,但没有打印任何内容。但是感谢您指出这个问题。
    • 其实发现有两个问题。这是一个,刚刚解决了另一个。也需要 lower() r[0]。
    【解决方案2】:

    在您的尝试中:text = l.find("li").get_text(strip=True)

    Soup 和 html 通常会增加大量空白。如果您不使用 strip 参数解析它,那么您可能永远不会得到匹配,除非您的列表文件中包含空格。

    【讨论】:

    • 谢谢,这并没有解决问题。此外,当我打印这些值时,我也没有看到额外的空白,它们似乎是完全匹配的。
    • Np,很高兴你得到了答案,并希望我的回答对未来的其他项目有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2022-07-16
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2017-12-31
    相关资源
    最近更新 更多