【问题标题】:How do I get value of tags while scraping a website with python?如何在使用 python 抓取网站时获取标签的价值?
【发布时间】:2020-08-06 02:29:38
【问题描述】:

我正在尝试抓取一个网站,这是 HTML 代码

<h2>Information</h2>
<div>
  <span class="dark_text">Type:</span>
  <a href="https://myanimelist.net/topanime.php?type=tv">TV</a>
</div>
<div class="spaceit">
  <span class="dark_text">Episodes:</span>
  12
</div>
<div class="spaceit">
  <span class="dark_text">Duration:</span>
  25 min. per ep.
</div>

我正在尝试在完整的 html 代码中获取 Episodes: & 12Duration: & 25 min. per ep. 以及更多类似的内容。

我希望这些值作为字符串

我的python代码是

page_soup = soup(page_html, "html.parser")

spaceit = page_soup.findAll("div",{"class": "spaceit"})

我不知道如何找到spandiv 的值

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

使用 select 然后运行 ​​for 循环

例子

from bs4 import BeautifulSoup

html = '<h2>Information</h2>' \
       '<div>' \
       '<span class="dark_text">Type:</span>' \
       '<a href="https://myanimelist.net/topanime.php?type=tv">TV</a>' \
       '</div>' \
       '<div class="spaceit">' \
       '<span class="dark_text">Episodes:</span>12</div>' \
       '<div class="spaceit">' \
       '<span class="dark_text">Duration:</span>25 min. per ep.</div> '

page_soup = BeautifulSoup(html, features="lxml")
elements = page_soup.select('div.spaceit')

for element in elements:
    print(element.get_text())

【讨论】:

猜你喜欢
  • 2022-01-08
  • 1970-01-01
  • 2019-09-22
  • 2019-04-26
  • 2022-08-18
  • 2020-05-28
  • 2016-09-04
  • 1970-01-01
  • 2020-09-28
相关资源
最近更新 更多