【发布时间】:2016-10-28 08:09:54
【问题描述】:
如何从下面引用的页面中删除(或编码)特殊字符?
import urllib2
from bs4 import BeautifulSoup
import re
link = "https://www.sec.gov/Archives/edgar/data/4281/000119312513062916/R2.htm"
request_headers = {"Accept-Language": "en-US,en;q=0.5", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Referer": "http://google.com", "Connection": "keep-alive"}
request = urllib2.Request(link, headers=request_headers)
html = urllib2.urlopen(request).read()
soup = BeautifulSoup(html, "html.parser")
soup = soup.encode('utf-8', 'ignore')
print(soup)
【问题讨论】:
-
真正的问题是什么?为什么在打印之前对结果进行编码? Stdout 将编码为您的终端语言环境。
-
我认为问题是因为您在解析 html 时出错? charset=us-ascii 所以不需要编码任何东西,问题是 html 被破坏了。您将需要一个不同的解析器,html5lib 和 lxml 设法解析它,但聪明的 html 谁知道它有多好。
标签: python utf-8 beautifulsoup ascii