【问题标题】:List Not Displaying The Values Only The Name For The Item列表不显示值仅显示项目的名称
【发布时间】:2021-02-24 01:12:15
【问题描述】:

我正在编写一个小脚本来从 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

【问题讨论】:

    标签: python python-requests-html


    【解决方案1】:

    看起来您需要访问这些值(而不是键的名称,正如当前在 .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'}
    ...
    

    【讨论】:

    • 这似乎行得通。是否可以删除链接部分周围的{' '}?谢谢你的回答!
    • 没问题!你可以做类似print(t['title'], t['link'].replace('{', '').replace('}', '') 的事情。这只会用任何内容替换这些字符的任何实例。
    • 感谢您的建议,但它给了我一个错误AttributeError: 'set' object has no attribute 'replace'。我正在考虑使用.strip(),但不知道如何让它为我想做的事情工作。
    • 啊,我的错。如果您首先将链接转换为字符串,然后仅包含内引号,则它应该正确格式化。 str(t['link']).replace("{\'", "").replace("\'}", "")
    • 谢谢伙计,现在一切正常。祝你有美好的一天!
    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多