簡體   English   中英

Python:查找網站語言的腳本

[英]Python: a script to find the website language

大家好,

我正在嘗試在 Python 中編寫一個程序來自動檢查網站語言。 我的腳本查看 HTML header,確定字符串“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 header 檢索語言的方法,但它沒有開發,也沒有建議任何代碼,所以我認為這篇文章是相當不同的。

非常感謝你,祝你有美好的一天,Berti

你可以試試這個:

import requests

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

如果您有興趣從頁面源獲取數據。 這可能會有所幫助。

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

結合以上反應

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM