python - 如何使用beautifulsoup从网页中正确提取特殊字符?

标签 python html utf-8 beautifulsoup

我正在尝试使用 beautifulsoup 从给定 url 的网页中提取所有文本。 我尝试运行在这里找到的代码:https://www.researchgate.net/post/how_to_scrape_text_from_webpage_using_beautifulsoup_python

除“é”或“à”等特殊字符外,一切正常。 我尝试了一系列修改,但无法正常工作。 这是我的代码:

from bs4 import BeautifulSoup
import requests
import re
import codecs

html = requests.get(yourWebsiteURL).content

unicode_str = html.decode('utf8')
encoded_str = unicode_str.encode("ascii",'ignore')
news_soup = BeautifulSoup(encoded_str, "html.parser")
a_text = news_soup.find_all('p')

y=[re.sub(r'<.+?>',r'',str(a)) for a in a_text]

file = codecs.open("textOutput.txt", "wb", encoding='utf-8')
file.write(str(y))
file.close()

但是,我确信问题出在我对 bs4 的使用上,因为我在写入文件时从未遇到过这个问题。

最佳答案

encoded_str = unicode_str.encode("ascii",'ignore')

这行代码将您的文本编码为 ascii。 Ascii 不包含特殊字符,例如 é 或 à。我不确定为什么要从包含这些字符的 UTF8 解码为不包含这些字符的 ascii。

关于python - 如何使用beautifulsoup从网页中正确提取特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50095114/

相关文章:

python - Hadoop流无法访问jar存档

python - Pandas 在堆栈上的行为

php - php mysql 中的UTF8

python - 无法与 CX-Oracle 一起使用

Python 导入错误 : No module named psycopg2

jquery - 在 jquery 中使用 overflow=hidden 获取窗口高度

HTML5 缓冲视频并无缝播放

html - 有没有办法改变输入类型 ="date"格式?

java - 将 JSON 中的特殊字符从 android 发送到 PHP

wordpress - 输入希伯来语时,PayPal 捐赠说明显示断线字符