Python - 如何获取维基百科将我重定向到的页面?

问题描述 投票:0回答:4

我想存储一些不同的维基百科链接,但我不想将同一页面的两个不同链接存储两次。例如,以下链接不同,但它们指向相同的维基百科页面:

https://en.wikipedia.org/w/index.php?title=(1S)-1-Methyl-2,3,4,9-tetrahydro-1H-pyrido-3,4-b-indole&redirect=no 
https://en.wikipedia.org/w/index.php?title=(1S)-1-methyl-2,3,4,9-tetrahydro-1H-pyrido-3,4-b-indole&redirect=no
__________________________________________________|___________________________________________________________

唯一的区别是多了一个大写字符。或以下链接:

https://en.wikipedia.org/wiki/(0,1)-matrix 
https://en.wikipedia.org/wiki/(0,1)_matrix 
___________________________________|______ 

这只是因为一个有“-”而另一个有“_”(“”)。所以我想要的是只存储其中之一或以下链接:

https://en.wikipedia.org/wiki/Tetrahydroharman 
https://en.wikipedia.org/wiki/Logical_matrix 

我已经尝试过这个SO问题的答案。但这对我不起作用。 (结果是我的初始 URL,而不是 wiki 在浏览器中将我重定向到的那个 URL)那么我怎样才能实现我正在寻找的东西!?

python python-3.x http python-requests redirect
4个回答
6
投票

MediaWiki Action API 提供维基百科中使用的各种端点。您可以查询端点https://en.wikipedia.org/w/api.php来获取重定向的目标页面。

您可以将结果作为 JSON 检索并解析它以获取元素

to 或元素 title 的值

示例:

此查询将检索“Halab”城市的目标页面:

https://en.wikipedia.org/w/api.php?action=query&titles=Halab&redirects&format=json

结果:

{ "batchcomplete":"", "query":{ "redirects":[ { "from":"Halab", "to":"Aleppo" } ], "pages":{ "159244":{ "pageid":159244, "ns":0, "title":"Aleppo" } } } }
Python 中:

import json import requests query = requests.get(r'https://en.wikipedia.org/w/api.php?action=query&titles={}&redirects&format=json'.format('Halab')) data = json.loads(query.text)
    

4
投票
由于维基百科没有正确的 301/302 重定向,因此当您打开链接时会返回正确的 200 成功响应,然后使用 JS 更改 url

我想出了一个快速可行的解决方案。首先,从 URL 中删除

&redirect=no

 

In [42]: import requests In [43]: r = requests.get('https://en.wikipedia.org/w/index.php?title=(1S)-1-Met ...: hyl-2,3,4,9-tetrahydro-1H-pyrido-3,4-b-indole') In [44]: tmp = r.content.replace('<link rel="canonical" href="', 'r@ndom}-=||'). ...: split('r@ndom}-=||')[-1] In [45]: idx = tmp.find('"/>') In [46]: real_link = tmp[:idx] In [47]: real_link Out[47]: 'https://en.wikipedia.org/wiki/Tetrahydroharman'

真实的URL值存储在

<link rel="canonical" href="

标签中。

您可以使用上述方法,这对于您的用例来说足够好,或者您可以使用 bs4 等库来解析页面并获取链接或使用正则表达式提取链接。


0
投票
Amit Tripathi 的回答抛出了一个异常。这是我的回答:

res = requests.get(url) doc = lxml.html.fromstring(res.content) for t in doc.xpath("//link[contains(@rel, 'canonical')]"): new_url = str(t.attrib['href'])

根据我的经验,可能会重定向到相同的网址。所以在使用 new_url 之前最好检查一下 (url != new_url)。


0
投票
这是使用

wikipedia

 库的非常简单的解决方案:

>>> import wikipedia >>> page = wikipedia.page(title="(0,1)_matrix", redirect=True) >>> page.title 'Logical matrix'
    
© www.soinside.com 2019 - 2024. All rights reserved.