我必须下载HTML页面的源代码,然后找到特定的标题并将其打印在Python的GUI上。我能够下载HTML文件,但是无法在下载的HTML页面中找到我感兴趣的元素。例如,我当前正在使用此网页。
https://www.metacritic.com/browse/games/release-date/coming-soon/all/date
第一个发布的游戏是“ Lovecraft的不为人知的故事”。我想要这个标题并在我的GUI中打印。在HTML页面中,该标题是通过
def game_function():
game = Tk()
game.geometry('600x400')
game.title('Upcoming Video Game Releases')
game.resizable(0,0)
opener = urllib.request.FancyURLopener({})
url = "file:///D:/Riz/Poppie%202/Upcoming%20Video%20Game%20Releases%20for%202019%20-%20Metacritic.html"
with urllib.request.urlopen(url) as response:
encoding = response.info().get_param('charset', 'utf8')
html = response.read().decode(encoding)
print("",html)
title_tag = '<h3>(.*)</h3>'
title_1 = findall(title_tag, html)
print("",title_1)
title1_subtitle = Label(game, text = title_1, bg='white', fg='black', font = ('Arial', 14, 'bold'))
title1_subtitle.place(relx=0.8, rely=0.49)
title1_subtitle.configure(wraplength='260')
game.mainloop()
答案 0 :(得分:1)
问题是由于\n
标记内有换行符(h3
)引起的。在re.findall
的第一个参数中,.
表示除换行符之外的任何字符,除非您使用re.DOTALL
作为第三个参数。此外,您应该使用非贪婪版本。
我希望下面的例子可以清楚地说明这一点:
import re
txt = '''<h3>
SomeTitle
</h3>
AnotherContent
<h3>
AnotherTitle
</h3>'''
nodotall = re.findall('<h3>(.*)</h3>',txt)
withdotall = re.findall('<h3>(.*)</h3>',txt,re.DOTALL)
nongreedy = re.findall('<h3>(.*?)</h3>',txt,re.DOTALL)
print(nodotall) # [] i.e. nothing found
print(withdotall) # ['\nSomeTitle\n</h3>\nAnotherContent\n<h3>\nAnotherTitle\n'] i.e. everything between first <h3> and last </h3>
print(nongreedy) # ['\nSomeTitle\n', '\nAnotherTitle\n'] i.e. desired output