我已经创建了一个爬虫。现在我已经抓取了一堆 URL。 我需要使用向量空间或至少 HTML 中所有术语的列表来创建索引。
假设这个随机网页 https://www.centralpark.com/things-to-do/central-park-zoo/polar-bears/
如何解析该网页中的所有术语?我有点不明白我应该抓取特定标签之间的文本还是其他东西或者我应该使用哪个库?我完全迷失了。
这是我需要对该 HTML 执行的操作:
You can use a html parser online, but in principle, you can use the text in the body of the html ... or between tags like this p /p, h2 /h2.
任何解析上述 HTML 的帮助都会受到赞赏。
编辑: 我正在尝试 BeautifulSoup:
import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url='https://www.centralpark.com/things-to-do/central-park-zoo/polar-bears/'
# opening up connection
uClient = uReq(my_url)
page_html = uClient.read()
# close connection
uClient.close()
page_soup = soup(page_html, features="html.parser")
print(page_soup.p)
如何将所有文本元素放入List?
例如:
<p>This is p<\p>
<p>This is another p<\p>
<h1>This is h1<\h1>
maybe some other text tags
至
List = ['This is p','This is another p','This is h1',...]
最佳答案
很好,你正在进步!
我建议您pip install requests
并使用它。您会发现它是一个比 urllib 方便得多的 API。 (此外,简单地 soup
将是该变量的常用名称。)
How to take all text elements in to List?
就这么简单:
print(list(page_soup.find_all('p')))
这解释了为什么这么多人非常喜欢BeautifulSoup。
这将显示页面摘录:
paragraphs = page_soup.find_all('p')
for p in paragraphs:
print(str(p)[:40])
<p class="lead">There are no longer any
<p><strong>Polar Bear</strong> (Ursus Ma
<p><strong>Zoo collection includes:</str
<p><strong>Found in the wild:</strong> A
<p><strong>See Them at the Central Park
<p><strong>Description:</strong> The mal
<p><strong>Zoo Bear Habitat:</strong> Th
<p><strong>What do they eat:</strong> T
<p><strong>Life span:</strong> 25 to 30
<p><strong>Threats:</strong> Global warm
<p><strong>Fun Facts:</strong> A newborn
<p>Copyright © 2004 - 2018 Greensward Gr
需要注意的是p
不是字符串。
它是一个可以被搜索的物体,就像它来自的汤一样。
您可能想查找<strong>
跨越其中。
关于python - 解析 HTML 以检索术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684293/