gpt4 book ai didi

python - 如何在 python 中获取 `http-equiv`?

转载 作者:可可西里 更新时间:2023-11-01 16:29:12 25 4
gpt4 key购买 nike

我正在使用 urllib2.urlopen获取 URL 并获取标题信息,如“字符集”、“内容长度”。

但是有些页面用类似的东西设置了他们的字符集

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

urllib2不为我解析这个。

有没有我可以用来获取 http-equiv 的内置工具?信息?

编辑:

这就是我解析 charset 所做的从一个页面

elem = lxml.html.fromstring(page_source)
content_type = elem.xpath(
".//meta[translate(@http-equiv, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='content-type']/@content")
if content_type:
content_type = content_type[0]
for frag in content_type.split(';'):
frag = frag.strip().lower()
i = frag.find('charset=')
if i > -1:
return frag[i+8:] # 8 == len('charset=')

return None

我该如何改进?我可以预编译 xpath 查询吗?

最佳答案

使用 BeautifulSoup 查找“http-equiv”

import urllib2
from BeautifulSoup import BeautifulSoup

f = urllib2.urlopen("http://example.com")
soup = BeautifulSoup(f) # trust BeautifulSoup to parse the encoding
for meta in soup.findAll('meta', attrs={
'http-equiv': lambda x: x and x.lower() == 'content-type'}):
print("content-type: %r" % meta['content'])
break
else:
print('no content-type found')

#NOTE: strings in the soup are Unicode, but we can ask about charset
# declared in the html
print("encoding: %s" % (soup.declaredHTMLEncoding,))

关于python - 如何在 python 中获取 `http-equiv`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4352468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com