Skip to main content
 首页 » 编程设计

python之如何加载网页(不在浏览器中)然后获取该网页的网址

2025年05月04日13lovecherry

我想做一些我在 Reddit 上看到的东西,让你可以随机获得一篇维基百科文章,查看它的标题,然后选择 A(在浏览器中打开文章)或 B(随机获得一篇新文章)。要获得一篇随机文章,您可以输入此 URL“https://en.wikipedia.org/wiki/Special:Random”,但随后我需要重新加载该 URL,看看它发生了什么变化,然后找出我得到的文章。我该怎么做?

请您参考如下方法:

将任务分解成小块:

get a random Wikipedia article

很酷。这很简单。您可以使用 Python 的内置 urllib2 或 requests 包。大多数人推荐 requests (pip install requests),因为它是一个更高级的库,使用起来更简单,但在这种情况下,我们所做的非常简单可能有点矫枉过正。无论如何:

import requests 
 
RANDOM_WIKI_URL = "https://en.wikipedia.org/wiki/Special:Random" 
response = requests.get(RANDOM_WIKI_URL) 
data = response.content 
url = response.url 

see its headline

为此我们需要解析 HTML。很容易建议您只使用正则表达式从包含标题的元素中提取文本,但实际上做这种事情的正确方法是使用像 BeautifulSoup 这样的库(pip安装 beautifulsoup4):

from bs4 import BeautifulSoup 
soup = BeautifulSoup(data, 'html.parser') 
title = soup.select('#firstHeading')[0].get_text() 
print title 

either A ([...]) or B ([...])

print "=" * 80 
print "(a): Open in new browser tab" 
print "(b): Get new article" 
print "(q): Quit" 
user_input = raw_input("[a|b|q]: ").lower() 
 
if user_input == 'a': 
    ... 
elif user_input == 'b': 
    ... 
elif user_input == 'q': 
    ... 

open the article in your browser

import webbrowser 
 
webbrowser.open_new_tab(url) 

get a new random article

response = requests.get(RANDOM_WIKI_URL) 
data = response.content 
url = response.url 

综合:

from __future__ import unicode_literals 
 
import webbrowser 
 
from bs4 import BeautifulSoup 
import requests 
 
 
RANDOM_WIKI_URL = "https://en.wikipedia.org/wiki/Special:Random" 
 
 
def get_user_input(): 
    user_input = '' 
    while user_input not in ('a', 'b', 'q'): 
        print '-' * 79 
        print "(a): Open in new browser tab" 
        print "(b): Get new random article" 
        print "(q): Quit" 
        print '-' * 79 
        user_input = raw_input("[a|b|q]: ").lower() 
    return user_input 
 
def main(): 
    while True: 
        print "=" * 79 
        print "Retrieving random wikipedia article..." 
        response = requests.get(RANDOM_WIKI_URL) 
        data = response.content 
        url = response.url 
 
        soup = BeautifulSoup(data, 'html.parser') 
        title = soup.select('#firstHeading')[0].get_text() 
 
        print "Random Wikipedia article: '{}'".format(title) 
        user_input = get_user_input() 
        if user_input == 'q': 
            break 
        elif user_input == 'a': 
            webbrowser.open_new_tab(url) 
 
 
if __name__ == '__main__': 
    main()