python - 解析 HTML 以检索术语

标签 python python-3.x html-parsing

我已经创建了一个爬虫。现在我已经抓取了一堆 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/

相关文章:

python - 如何使用 boto 在 Windows ec2 实例上安装临时存储?

ruby - Ruby 中可用的网页抓取 gem /工具

python - 在 Python 应用程序中嵌入 Python 解释器

python - 对于 Python2 到 Python3 的代码转换,哪个版本的 Python 和 Django 最适合?

python - Django-Debug-Toolbar 未显示(不允许的 MIME 类型)

python - 情节 AttributeError : 'Figure' object has no attribute 'update_layout'

python - 在读取实际行之前,如何自动解析打开的audit.log 文件的语法?

Python 3打印到文件创建错误的新行

javascript - 用 JS 解析 HTML 字符串

html - 即 : position two text lines on top and bottom corners in table cell?