【发布时间】:2023-03-21 21:15:02
【问题描述】:
我正在尝试从给定 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 标签都消失了),但它们变成了 markdown 语法。
# 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]
有没有办法排除markdown标签(尤其是图片和url链接)并有更好的句子?
【问题讨论】:
-
由于 markdown 接受 HTML,您可能需要先尝试通过 markdown 解析器运行初始文本,然后解析生成的 HTML(markdown 现在变成 HTML)。
标签: python web-scraping