首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python3中,当html包含标记语法时,如何更好地应用html2text()

在Python3中,当html包含标记语法时,如何更好地应用html2text()
EN

Stack Overflow用户
提问于 2016-12-23 09:20:46
回答 2查看 2.5K关注 0票数 0

我试图从一个给定的URL中抓取可见的文本。

它应该适用于任何随机的url,所以我不能预先假定html标记、元素、布局等等。知道完美的爬行似乎很困难,我只是希望包括大部分的自然语言部分,而不包括大多数非自然语言部分。

到目前为止,我发现结合使用BeautifulSouphtml2text似乎相当不错。

下面是我的骨架代码。

代码语言:javascript
复制
url = 'https://en.wikipedia.org/wiki/Autonomous_car'
req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"})

cj = CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
response = opener.open(req)
html = response.read().decode('utf8', errors='ignore')
response.close()

# Get html string
soup = BeautifulSoup(html, "lxml")
htmltext = soup.encode('utf-8').decode('utf-8','ignore')
html2text.html2text(htmltext)

然后,我得到了如下的文本,这些文本并不坏(所有的html标记都消失了),但是它们会产生标记语法。

代码语言:javascript
复制
# Autonomous car

From Wikipedia, the free encyclopedia

Jump to: navigation, search

For the wider application of artificial intelligence to automobiles, see [Unmanned ground vehicle](/wiki/Unmanned_ground_vehicle "Unmanned ground vehicle" ) and [Vehicular automation](/wiki/Vehicular_automation "Vehicular Automation").

[![](//upload.wikimedia.org/wikipedia/commons/thumb/6/65/Hands-free_Driving.jpg/230px-Hands-free_Driving.jpg)](/wiki/File:Hands free_Driving.jpg)

Junior, a robotic [Volkswagen Passat](/wiki/Volkswagen_Passat "Volkswagen Passat" ), at [Stanford University](/wiki/Stanford_University "Stanford University" ) in October 2009.

An **autonomous car** (**driverless car**,[1] **self-driving car**,[2] **robotic car**[3]) is a [vehicle](/wiki/Vehicular_automation "Vehicular automation" ) that is capable of sensing its environment and navigating without human input.[4]

有没有办法排除标价标签(尤指标签)。图片和网址链接)和有一个更好的句子?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-24 17:27:38

我发现html2text从给定的html 中提取文本,其中包含链接和标记语法中的图像。

因此,您可以通过以下方法来管理一些选项,而不是使用,html2text.html2text(htmltext)

代码语言:javascript
复制
h = html2text.HTML2Text()
h.ignore_links = True
h.ignore_images = True
h.handle (htmltext)
票数 0
EN

Stack Overflow用户

发布于 2021-12-29 15:14:43

对于那些想忽略所有标记语法的人:

代码语言:javascript
复制
import html2text

htmlParser = html2text.HTML2Text()
htmlParser.body_width = 2 ** 31 - 1
htmlParser.handle_tag = lambda *args, **kwargs: None
htmlText = "<ul><li><quote><b>Hello World</b></quote></li></ul>"
print("Old: @{}@".format(html2text.html2text(htmlText).strip()))
print("New: @{}@".format(htmlParser.handle(htmlText).strip()))

输出:

代码语言:javascript
复制
Old: @* **Hello World**@
New: @Hello World@
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41298542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档