【问题标题】:Is BeautifulSoup up to the task? [closed]BeautifulSoup 能胜任这项任务吗? [关闭]
【发布时间】:2019-07-01 21:37:23
【问题描述】:

我一直在尝试从一个似乎有多个 html 级别的网站中提取一些数据。从我看到的所有示例中,我想到 BeautifulSoup 是一个很棒的产品,如果你试图找到嵌套在树下不那么远的数据。

对于我的小项目,我正在尝试让 BeautifulSoup 从以下位置提取数据。

任何帮助将不胜感激。

<html lang=“en”>
<body>
<div id=“wrapper”>
<div id=“app_timeline”>
<div id=“timeline-summary”
<div id=“timeline-summary-sticky”>
<div class=“summary-list”>
<div>
<div class=“summary-type”>
<div class=“details”>
<div class=“value”>
<div>
<span class=“number”>100</span>

数字 100 每天都在变化,所以我想写一些东西,当我运行一些 python 代码时可以提取这些数据。

TIA

【问题讨论】:

标签: python html beautifulsoup nested


【解决方案1】:

我会使用 Selenium,我有一段时间没有使用 beautifulsoup。我发现 Selenium 更容易提取数据。您可以通过多种方式找到元素,其中一种是按类。

from selenium import webdriver
chromedriver = 'location of driver'
driver = webdriver.Chrome(chromedriver)
driver.get('url')
data = driver.find_element_by_class('number').text #this would return the first time the class of number is found
data = driver.find_elements_by_class('number') #this would return all the class of numbers

【讨论】:

  • 我会试一试并报告...感谢您抽出时间提供帮助:)
【解决方案2】:

对于此任务,您可能需要使用soup.find() 方法。 soup.find() 可以帮助您导航到特定的 html 标签,即 &lt;class&gt;&lt;div&gt;。在变量上调用.text 将允许您在&lt;span&gt; &lt;/span&gt; 标记之间获取文本。所以,在你的例子中,你会想尝试

import urllib2
from bs4 import BeautifulSoup    

url = "your_url"
response = urllib2.build_opener(urllib2.HTTPCookieProcessor).open(url)
html_doc = response.read()

soup = BeautifulSoup(html_doc, 'html.parser')

print(soup.body.find("span").text)

输出: 100

如果您希望能够存储此值并在以后使用它,请将soup.body.find("span").text 分配给一个变量。尝试查看此link 以熟悉 BeautifulSoup。

【讨论】:

  • 这肯定只是要从脚本本身中提取数据吗?随着数据每天变化,我需要它从目标站点获取 吗?
  • @Andy 我添加了代码行供您输入您的 URL。我根据您提供的 HTML 编写了初始脚本。
猜你喜欢
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 2014-11-04
  • 2011-10-02
相关资源
最近更新 更多