首页 > 解决方案 > 用 BeautifulSoup 提取的链接不等同于相同的字符串

问题描述

我正在使用 BeautifulSoup 和 Requests 包的组合来制作一个简单的网络抓取脚本。

使用 Requests 包,我创建了主页的响应对象并将文本属性读取到文本文件。然后,使用 BeautifulSoup,我从响应对象的文本属性中过滤掉文本文件中的每个链接,并将它们全部附加到一个列表中。

url = 'http://sssscomic.com/' 
r = requests.get(url)
most_recent = r.text

with open('text.txt') as f_obj:
    f_obj.write(most_recent)

links = []

with open('text.txt','r') as f_obj:
    text = f_obj.read()
    soup = BeautifulSoup(text, 'html.parser', parse_only=SoupStrainer('a'))
    for link in soup.find_all('a'):
        links.append(link.get('href'))

现在这是踢球者。打印链接时,它返回以下内容:

['comic2.php?page=321', 'http://sssscomic.com/', 'comic.php?page=1', 'https://twitter.com/sssscomic', 'https://www.facebook.com/pages/Stand-Still-Stay-Silent-webcomic/655890117765567', 'https://www.instagram.com/hummingfluff/', 'https://www.twitch.tv/hummingfluff', 'http://sssscomic.com/ssss-feed.xml', '?id=about', '?id=archive', '?id=characters', '?id=misc', 'https://hivemill.com/collections/stand-still-stay-silent', 'http://sssscomic.com/comic.php?page=1', 'https://hivemill.com/collections/stand-still-stay-silent', 'https://hivemill.com/collections/stand-still-stay-silent']

列表中的第一项comic2.php?page=321正是我要查找的内容,但是当我将其保存到变量中并将其与该列表的结果进行比较时,计算机不会将它们识别为相等的。

last_recent = 'comic2.php?page=321'

if last_recent == str(links[0]):
    print('This should be triggering') 
if last_recent != str(links[0]): 
    print('But instead this is') 

我不知道这里发生了什么,但我尝试过的所有其他网站都会发生这种情况。我不太熟悉 html 的奥秘或 BeautifulSoup 库,但我怀疑问题出在这些领域之一。或者我可能完全错了,我对此还是很陌生。有人知道发生了什么吗?

标签: pythonhtmlpython-3.xbeautifulsoup

解决方案


好的,明白了。

感谢 hjpotter92 指出 repr() 方法。我实际上是从文件中读取 last_recent ,因此,它在 str() 未显示的字符串末尾添加了一个额外的 '\n' 。


推荐阅读