在Python爬蟲中,處理亂碼問題通常涉及到兩個方面:一是解析網頁內容時可能遇到的編碼問題;二是提取文本信息時可能遇到的特殊字符。以下是一些建議來處理這些問題:
當使用requests庫獲取網頁內容時,可以通過檢查響應頭中的Content-Type
字段來確定網頁的編碼格式。例如:
import requests
url = 'http://example.com'
response = requests.get(url)
content_type = response.headers.get('Content-Type', '')
encoding = 'utf-8'
if 'charset=' in content_type:
encoding = content_type.split('charset=')[-1]
html_content = response.content.decode(encoding)
在提取文本信息時,可能會遇到一些特殊字符,如HTML標簽、JavaScript代碼等??梢允褂谜齽t表達式來匹配和處理這些特殊字符。例如,使用re
庫來提取純文本內容:
import re
html_content = '''
<html>
<head>
<title>Example</title>
</head>
<body>
<p>Some <b>text</b> with special characters: & < ></p>
<script>console.log("Hello, world!");</script>
</body>
</html>
'''
# 使用正則表達式匹配純文本內容,排除HTML標簽和腳本
text = re.sub(r'<[^>]+>', '', html_content)
text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.DOTALL)
print(text)
輸出結果:
Some text with special characters: & < >
這樣,你就可以使用正則表達式來處理亂碼問題了。如果還有其他問題,請隨時提問。