【问题标题】:Python: a script to find the website languagePython:查找网站语言的脚本
【发布时间】:2019-10-11 10:56:15
【问题描述】:

大家好,

我正在尝试用 Python 编写一个程序来自动检查网站语言。我的脚本查看 HTML 标头,确定字符串“lang”出现的位置,然后打印相应的语言。我使用模块“请求”。

request = requests.get('https://en.wikipedia.org/wiki/Main_Page')
splitted_text = request.text.split()
matching = [s for s in splitted_text if "lang=" in s]
language_website = matching[0].split('=')[1]
print(language_website[1:3])

>>> en

我已经在几个网站上对其进行了测试,并且它可以正常工作(假设语言首先在 HTML 中正确配置,这很可能适用于我在研究中考虑的网站)。

我的问题是:是否有更直接/一致/系统的方式来实现相同的目标。如何使用 python 查看 HTML 并返回网站编写的语言?例如使用 lxml 有没有更快的方法(不涉及像我一样解析字符串)?

我知道之前有人问过如何查找网站语言的问题,并且提到了使用HTML头检索语言的方法,但是没有开发,没有代码建议,所以我认为这个帖子是相当不同。

非常感谢!度过美好的一天, 贝尔蒂

【问题讨论】:

标签: python html python-3.x python-requests


【解决方案1】:

你可以试试这个:

import requests

request = requests.head('https://en.wikipedia.org/wiki/Main_Page')
print(request.headers["Content-language"])

【讨论】:

  • 非常感谢!你的代码比我的要优雅得多,但它返回 KeyError: 'content-language' 在某些网站(不是维基百科)的情况下。比如这个:asia.christianlouboutin.com/tw_tc
【解决方案2】:

如果您有兴趣从页面源获取数据。这可能会有所帮助。

import lxml
request = requests.get('https://en.wikipedia.org/wiki/Main_Page')
root = lxml.html.fromstring(request.text)
language_construct = root.xpath("//html/@lang") # this xpath is reliable(in long-term), since this is a standard construct.

language = "Not found in page source"
if language_construct:
      language = language_construct[0]
print(language)

注意:此方法不会为所有网页提供结果,只会为包含 HTML 语言代码参考的网页提供结果。

更多信息请参考https://www.w3schools.com/tags/ref_language_codes.asp。

【讨论】:

  • 你的代码很棒,它让我对 lxml 更加熟悉了!非常感谢您的帮助。只有两件非常小的事情:在我的情况下,我必须专门添加:'from lxml import html',否则由于某种原因模块不存在。就我而言,我不想要'en-AU'之类的东西,而只想要'en',所以我写了'language = language_construct[0].split('-')[0]'。再次谢谢你:)
【解决方案3】:

结合以上反应

import requests
request = requests.head('https://en.wikipedia.org/wiki/Main_Page')
print(request.headers.get("Content-language", "Not found in page source"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 2016-02-16
    相关资源
    最近更新 更多