【问题标题】:How can I add hyperlinks to a tkinter Text() widget?如何将超链接添加到 tkinter Text() 小部件?
【发布时间】:2021-04-30 14:21:30
【问题描述】:

我正在开发一个程序,从 news.ycombinator.com 抓取前十篇文章

现在一切都按照我想要的方式工作,但我想为我的 tkinter Text() 小部件中显示的所有链接添加超链接。

如何为我抓取的每个“链接”添加超链接?

screenshot of tkinter window

刮刀

import requests
from bs4 import BeautifulSoup
import hn_gui

res = requests.get(f'https://news.ycombinator.com/news')
soup = BeautifulSoup(res.text, 'html.parser')
links = soup.select('.storylink')
subtext = soup.select('.subtext')


def sort_stories_by_votes(hnlist):
    return sorted(hnlist, key=lambda k: k['votes'], reverse=True)


def create_custom_hn(links, subtext):
    hn = []
    for idx, item in enumerate(links):
        title = item.getText()
        href = item.get('href', None)
        vote = subtext[idx].select('.score')
        if len(vote):
            points = int(vote[0].getText().replace(' points', ''))
            if points > 99:
                hn.append({'title': title, 'link': href, 'votes': points})
    return sort_stories_by_votes(hn)


news = create_custom_hn(links, subtext)

hn_gui

Tkinter

from tkinter import *
from scraper import news

root = Tk()
root.title("Hacker News Top Ten")
text = Text(root, font=('Arial', 20), wrap="word")

for article in news:
    link = '{0} {1}'.format("Link:", article['link'])
    title = '{0} {1}'.format("\nTitle:", article['title'])
    votes = '{0} {1}'.format("\nVotes:", article['votes'])
    text.insert(INSERT, link)
    text.insert(INSERT, title)
    text.insert(INSERT, votes)
    text.insert(END, "\n\n")
text.config(bg="black", fg="grey")
text.pack(fill=BOTH, expand=1)

root.mainloop()

【问题讨论】:

标签: python tkinter web-scraping hyperlink


【解决方案1】:

根据@suraj_s 的建议,这是您的解决方案。我还将两个文件合并为一个

from tkinter import *
import requests, webbrowser
from bs4 import BeautifulSoup

res = requests.get(f'https://news.ycombinator.com/news')
soup = BeautifulSoup(res.text, 'html.parser')
links = soup.select('.storylink')
subtext = soup.select('.subtext')

def sort_stories_by_votes(hnlist):
    return sorted(hnlist, key=lambda k: k['votes'], reverse=True)

def create_custom_hn(links, subtext):
    hn = []
    for idx, item in enumerate(links):
        title = item.getText()
        href = item.get('href', None)
        vote = subtext[idx].select('.score')
        if len(vote):
            points = int(vote[0].getText().replace(' points', ''))
            if points > 99:
                hn.append({'title': title, 'link': href, 'votes': points})
    return sort_stories_by_votes(hn)


news = create_custom_hn(links, subtext)
#-------------------------------------------------
def callback(url):
    webbrowser.open_new(url)
    
root = Tk()
root.title("Hacker News Top Ten")
i = 0
for article in news:
    lbl = Label(root, text="Title: ")
    lbl.grid(row=i,column=0)
    lbl = Label(root, text=article['title'], fg="blue", cursor="hand2")
    lbl.grid(row=i,column=1)
    lbl.bind("<Button-1>", lambda e,url=article['link']: callback(url))
    lbl = Label(root, text="Votes: " + str(article['votes']))
    lbl.grid(row=i+1,column=0)
    i += 2

root.mainloop()

【讨论】:

  • 也许我做错了什么,但这似乎为每篇文章分配了相同的链接。
  • @AnonymouslyCognizant 尝试将lbl.bind("&lt;Button-1&gt;", lambda e: callback(article['link'])) 更改为lbl.bind("&lt;Button-1&gt;", lambda e, url=article['link']: callback(url))
  • 感谢@AnonymouslyCognizant,我更新了答案。现在它会相应地打开链接。
猜你喜欢
  • 2022-11-23
  • 2011-04-13
  • 2012-10-04
  • 1970-01-01
  • 2020-02-14
  • 2017-10-12
  • 1970-01-01
  • 2011-03-30
  • 2021-09-12
相关资源
最近更新 更多