【发布时间】:2020-12-10 11:19:35
【问题描述】:
我正在使用 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 库,但我怀疑问题出在这些领域之一。或者我可能完全错了,我对此还是很陌生。有人知道发生了什么吗?
【问题讨论】:
-
是python 2还是3?
-
是python3,我用的是最新版的BeautifulSoup
-
尝试打印
str和repr这两个值,而不是检查相等性。您可能会看到一些差异。 -
运行第一个示例代码时会引发异常。
-
hjpotter92 抓住了它!使用 repr 查看时,last_recent 实际上在其末尾有一个 '\n'。我认为这是因为在我的脚本中,我实际上是通过读取另一个文本文件来分配该变量。知道为什么 '\n' 将自身附加到文件中存储的字符串吗?
标签: python html python-3.x beautifulsoup