问题描述
我正在编写一个小脚本来从 TheTechGame.com 中提取线程并进行设置,以便将信息添加到列表中,但是当我遍历该列表以在终端中显示项目时,它只显示值而不是标题或链接。
代码:
from requests_html import HTMLSession
session = HTMLSession()
r = session.get("https://thetechgame.com/Forums/f=4/offtopic-discussion.html")
topic_title = r.html.find("a.topic-title")
topic_list = []
for topic_name in topic_title:
topic_info = {
'title': topic_name.text,'link': topic_name.absolute_links
}
topic_list.append(topic_info)
for items in topic_list:
print(' '.join(items))
输出:
title link
title link
...
title link
title link
我希望该线程的标题显示为 topic_name.text
,并在该标题之后显示链接 topic_name.absolute_links
。
解决方法
看起来您需要访问值(而不是键的名称,就像当前在 .join()
函数中发生的那样)。像这样的东西会给你听起来像你正在寻找的输出。在这里,您将遍历列表中的每个字典,然后使用 title
键和 link
键访问值。
for t in topic_list:
print(t['title'],t['link'])
这将为您提供以下输出:
TheTechGame Special Award Holders + Special Award Tutorials {'https://www.thetechgame.com/Forums/t=7462502/thetechgame-special-award-holders-special-award-tutorials.html'}
TTG All Time High Leaderboard {'https://www.thetechgame.com/Forums/t=7722177/ttg-all-time-high-leaderboard.html'}
...