Files
python/python爬虫/基于bs4库对html格式化与编码.py
2025-08-05 09:19:34 +08:00

19 lines
523 B
Python

import requests
from bs4 import BeautifulSoup
url = "https://python123.io/ws/demo.html"
header = {
"User-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.52'}
try:
r = requests.get(url, headers=header)
r.raise_for_status() # 检验是否出错
r.encoding = r.apparent_encoding # 编码一致
except:
print("出现异常")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
print(soup.prettify())
r.close()