我试图从一个给定的URL中抓取可见的文本。
它应该适用于任何随机的url,所以我不能预先假定html标记、元素、布局等等。知道完美的爬行似乎很困难,我只是希望包括大部分的自然语言部分,而不包括大多数非自然语言部分。
到目前为止,我发现结合使用BeautifulSoup和html2text似乎相当不错。
下面是我的骨架代码。
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标记都消失了),但是它们会产生标记语法。
# 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").
[](/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]有没有办法排除标价标签(尤指标签)。图片和网址链接)和有一个更好的句子?
发布于 2016-12-24 17:27:38
我发现html2text从给定的html 中提取文本,其中包含链接和标记语法中的图像。
因此,您可以通过以下方法来管理一些选项,而不是使用,html2text.html2text(htmltext)
h = html2text.HTML2Text()
h.ignore_links = True
h.ignore_images = True
h.handle (htmltext)发布于 2021-12-29 15:14:43
对于那些想忽略所有标记语法的人:
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()))输出:
Old: @* **Hello World**@
New: @Hello World@https://stackoverflow.com/questions/41298542
复制相似问题