【问题标题】:Scrape special characters in Python Beautiful Soup在 Python Beautiful Soup 中刮掉特殊字符
【发布时间】: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


【解决方案1】:

Unicode 对象只有在可以转换为 ASCII 时才能打印。如果它不能用 ASCII 编码,你会得到那个错误。您可能希望对其进行显式编码,然后打印结果汤:

import requests
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"}
reuest = requests.get(link, headers=request_headers)
soup = BeautifulSoup(reuest.text,"lxml")
print(soup.encode('utf-8'))

【讨论】:

  • 你完全改变了 OP 的代码,没有任何解释,但仍然保持相同的错误编码机制。 OP 想将html.parser 用于 BS,但您已经悄悄地换成了lxml。此外,您已经介绍了 requests 库,但在这里不是必需的。你对 Unicode 对象也是错误的——stdout 流将尝试编码为 shell 的编码。很少使用 ASCII 编码。因此,您应该允许标准输出根据需要进行编码并通过str 而不是bytes
猜你喜欢
  • 1970-01-01
  • 2018-04-22
  • 2022-07-20
  • 2018-11-07
  • 1970-01-01
  • 2022-07-16
  • 2021-03-11
  • 2016-02-27
  • 2014-02-08
相关资源
最近更新 更多