python - 用 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 库,但我怀疑问题出在这些领域之一。或者我可能完全错了,我对此还是很陌生。有人知道发生了什么吗?
解决方案
好的,明白了。
感谢 hjpotter92 指出 repr() 方法。我实际上是从文件中读取 last_recent ,因此,它在 str() 未显示的字符串末尾添加了一个额外的 '\n' 。
推荐阅读
- javascript - 如何迭代数据组并以列表形式返回
- python - Python Selenium - 我如何检查我们是否在 HTML 上有一个项目?
- python - Python中的并行/多处理(嵌套)循环并存储结果?
- oracle - Sqoop 错误:导入需要 --table 或 --query
- python - FFmpeg“管道”不适用于 mp4 文件?
- node.js - 如果我不首先使用 Promises 通过 AWS NodeJS Lambda 终端节点上传一张图片,则无法将多张图片上传到 AWS S3
- rabbitmq - pyflink 1.11 的 RabbitMQ 自定义表源和接收器
- vue.js - Vuetify v-spacer 没有效果
- arrays - CS50 / BEGINNER - C 中嵌套 for 循环中的分段错误
- javascript - 一旦用户已经将项目添加到列表中,如何禁用“添加”项目按钮?