在理解 BeautifulSoup 过滤时遇到问题

2024-02-28

有人可以解释一下美丽汤的过滤是如何工作的吗?我得到了下面的 HTML,我正在尝试从中过滤特定数据,但我似乎无法访问它。我尝试过各种方法,从收集所有class=g是为了只抓取该特定 div 中感兴趣的项目,但我只是没有返回或没有打印。

每个页面都有一个<div class="srg">div 有多个<div class="g">divs,我要使用的数据是其中的数据<div class="g">。其中每一个都有 多个 div,但我只对<cite> and <span class="st">数据。我正在努力了解过滤的工作原理,任何帮助将不胜感激。

我尝试单步遍历 div 并获取相关字段:

 soup = BeautifulSoup(response.text)   

 main = soup.find('div', {'class': 'srg'})
 result = main.find('div', {'class': 'g'})
 data = result.find('div', {'class': 's'})
 data2 = data.find('div')
 for item in data2:
     site = item.find('cite')
     comment = item.find('span', {'class': 'st'})

 print site
 print comment

我还尝试进入最初的 div 并找到所有内容;

 soup = BeautifulSoup(response.text) 

 s = soup.findAll('div', {'class': 's'})

 for result in s:
     site = result.find('cite')
     comment = result.find('span', {'class': 'st'})

 print site
 print comment

测试数据

<div class="srg">
    <div class="g">
    <div class="g">
    <div class="g">
    <div class="g">
        <!--m-->
        <div class="rc" data="30">
            <div class="s">
                <div>
                    <div class="f kv _SWb" style="white-space:nowrap">
                        <cite class="_Rm">http://www.url.com.stuff/here</cite>
                    <span class="st">http://www.url.com. Some info on url etc etc
                    </span>
                </div>
            </div>
        </div>
        <!--n-->
    </div>
    <div class="g">
    <div class="g">
    <div class="g">
</div>

UPDATE

在 Alecxe 的解决方案之后,我再次尝试使其正确,但仍然没有打印任何内容。所以我决定再看一下soup它看起来不一样。我之前在看response.text from requests。我只能认为BeautifulSoup修改response.text或者我第一次得到的样本完全错误(不知道如何)。然而,下面是基于我从一个例子中看到的新样本soup打印。下面是我尝试获取我想要的元素数据。

<li class="g">
<h3 class="r">
    <a href="/url?q=url">context</a>
</h3>
<div class="s">
    <div class="kv" style="margin-bottom:2px">
        <cite>www.url.com/index.html</cite> #Data I am looking to grab
        <div class="_nBb">‎
            <div style="display:inline"snipped">
                <span class="_O0"></span>
            </div>
            <div style="display:none" class="am-dropdown-menu" role="menu" tabindex="-1">
                <ul>
                    <li class="_Ykb">
                        <a class="_Zkb" href="/url?/search">Cached</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <span class="st">Details about URI </span> #Data I am looking to grab

更新尝试

到目前为止,我已经尝试采用 Alecxe 的方法,但没有成功,我走的路正确吗?

soup = BeautifulSoup(response.text)

for cite in soup.select("li.g div.s div.kv cite"):
    span = cite.find_next_sibling("span", class_="st")

    print(cite.get_text(strip=True))
    print(span.get_text(strip=True))

首先得到div带有类名srg然后找到所有具有类名的divs里面srg并获取该文本site and comment。以下是我的工作代码-

from bs4 import BeautifulSoup

html = """<div class="srg">
    <div class="g">
    <div class="g">
    <div class="g">
    <div class="g">
        <!--m-->
        <div class="rc" data="30">
            <div class="s">
                <div>
                    <div class="f kv _SWb" style="white-space:nowrap">
                        <cite class="_Rm">http://www.url.com.stuff/here</cite>
                    <span class="st">http://www.url.com. Some info on url etc etc
                    </span>
                </div>
            </div>
        </div>
        <!--n-->
    </div>
    <div class="g">
    <div class="g">
    <div class="g">
</div>"""

soup = BeautifulSoup(html , 'html.parser')
labels = soup.find('div',{"class":"srg"})

spans = labels.findAll('div', {"class": 'g'})

sites = []
comments = []

for data in spans:
    site = data.find('cite',{'class':'_Rm'})
    comment = data.find('span',{'class':'st'})
    if site:#Check if site in not None
        if site.text.strip() not in sites:
            sites.append(site.text.strip())
        else:
            pass
    if comment:#Check if comment in not None
        if comment.text.strip() not in comments:
            comments.append(comment.text.strip())
        else: pass

print sites
print comments

Output-

[u'http://www.url.com.stuff/here']
[u'http://www.url.com. Some info on url etc etc']

EDIT--

为什么你的代码不起作用

尝试一-

您正在使用result = main.find('div', {'class': 'g'})它将抓取单个且第一个遇到的元素,但第一个元素还没有div带有类名s。所以这段代码的下一部分将不起作用。

尝试二-

您正在打印site and comment这不在打印范围内。所以尝试在 for 循环内打印。

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

s = soup.findAll('div', {'class': 's'})

for result in s:
    site = result.find('cite')
    comment = result.find('span', {'class': 'st'})
    print site.text#Grab text
    print comment.text
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在理解 BeautifulSoup 过滤时遇到问题 的相关文章

随机推荐

  • 如何获取 Woocommerce 产品中的变体 ID

    我正在尝试进入一个插件 我正在编写产品的变体 ID 这是我写的 class mass public function construct add action woocommerce product after variable attri
  • Android minLines 和 maxLines 不能在同一个 TextView 中一起工作

    这里我只有 1 件商品ListView我展示了两个不同的TextViews末尾有不同颜色的ListView item 但问题是我想显示每个最多 3 行TextView但如果长度为TextView是小 但如果文本很大 它效果很好 当我添加an
  • 如何确保我的 django 项目正在使用我为其创建的虚拟环境?

    我知道已经有一个与此类似的问题 但我认为我想要的答案不存在 我是 django 的新手 我已经使用 virtualenv 和 django 项目创建了一个虚拟环境 但是我们如何知道我的项目正在使用虚拟环境的包而不是使用全局包 请给我一些详细
  • 在 Episerver 中截断 Xhtmlstring

    我需要获得截断的 Xhtmlstring 的 html 友好版本 因为截断时标签结尾可能会被截断 关于如何实现这一目标有什么想法吗 我想过先删除所有标签 然后进行剪切 但是 Episerver 内部是否有解决方案 或者这只是使用正则表达式进
  • Matplotlib 中的像素化动画

    我一直在使用 Matplotlib 的动画工具来制作动画人物 我注意到一个问题 对于具有大量帧的动画来说尤其明显 即图形的质量很快就会恶化 导致输出看起来像素化 模糊 例子 Messy grid lines pixelated output
  • 将 HTMLDocument 转换为可打印字符串

    我想将 Javascript DOM HTMLDcument 转换为可以写入文件的字符串 但是如何将 HTMLDocument 的字符串转换为 xml Update如果可能的话 我希望看到应用任何动态 JavaScript 渲染后生成的 h
  • Python从文件中删除一行或多行而不修改现有内容

    我必须根据文件中的用户输入删除字符串或字符串列表 我参考了下面的链接 一切正常 删除文件中的特定行 python https stackoverflow com questions 4710067 deleting a specific l
  • Jenkinsfile 中的 Jenkins 全局环境变量

    如何在 Jenkinsfile 中调用全局环境变量 例如 如果我有一个变量 name credentialsId value xxxx xxxx xxxxx xxxxxxxxx 如何在 groovy 脚本中使用它 I tried crede
  • 视差效果使元素延迟滚动

    我正在尝试复制此网站 www adidas co uk climazone 这些元素似乎只在用户滚动后轻微移动 我怎样才能实现这个目标 谢谢你 Here s DEMO http s codepen io CY5 debug vKkELx它实
  • 正则表达式匹配任何单词 - 没有非贪婪运算符

    我想将任何内容匹配到特定单词 例如 C 中的结束评论 但是 由于性能原因 我不想使用非贪婪运算符 例如 要匹配 C 注释 对于我的文件来说太慢了 有没有可能提高性能 当然可以 使用展开循环技术 http www softec lu site
  • 通过 Vagrant 在 Docker 中共享卷

    我有一个 Vagrant virtualbox 它托管一个 Docker 容器 主机有一个需要在虚拟机和容器中访问的文件夹 Host host path gt VM vagrant path gt Container docker path
  • 名称和尺寸来自 NSFont

    我试图在互联网上找到一些东西 但现在我没有答案 所以如果你能帮助我那就太好了 到目前为止 我有一个 NSFont 对象 但我想要字体的名称 如 NSString 和大小 这样我就可以输出它 就像是 NSFont fontWithName M
  • 在 NLTK 中使用斯坦福 NER Tagger 提取人员和组织列表

    我正在尝试使用 Python NLTK 中的斯坦福命名实体识别器 NER 提取人员和组织的列表 当我跑步时 from nltk tag stanford import NERTagger st NERTagger usr share sta
  • Susy:为给定的屏幕宽度(断点 px 值)创建网格,并且不知道单列的宽度(非内容优先方法)

    我在用着Susy http susy oddbird net 我未能利用内容优先的方法 并决定采用 window px widths first 起初我尝试了内容优先的方法 http adactio com journal 4523 到网格
  • scanf() 格式字符串中尾随空格有何影响?

    有什么区别scanf d and scanf d 在此代码中 区别在于格式字符串中的尾随空白 include
  • Python:忽略 xml.etree.ElementTree 中的名称空间?

    如何告诉 ElementTree 忽略 XML 文件中的命名空间 例如 我更愿意查询modelVersion 如声明1 而不是 http maven apache org POM 4 0 0 modelVersion 如声明2 pom
  • matplotlib:如何在图形上选择shift点击?

    我有一个 matplotlib 并且创建了一个button press event像这样 self fig canvas mpl connect button press event self onClick def onClick sel
  • PhpSpreadsheet 正在损坏文件

    我正在使用 PhpSpreadsheet 修改现有文件并将其发送到浏览器 但是每次下载文件 excel 都会出现以下错误 我们发现 filename xlsx 中的某些内容存在问题 您希望我们尽力恢复吗 如果您信任此工作簿的来源 请单击 是
  • 对(双精度)实数向量进行排序并获得它们

    在 C 中想要对很长的 2 20 实数向量 显然sort 就可以了 在我习惯了 R 的优点之前就已经使用过 Rorder 函数产生导致排序向量的排列 Example x 24 55 22 1 然后是排列 perm 3 2 0 1 贴出原图x
  • 在理解 BeautifulSoup 过滤时遇到问题

    有人可以解释一下美丽汤的过滤是如何工作的吗 我得到了下面的 HTML 我正在尝试从中过滤特定数据 但我似乎无法访问它 我尝试过各种方法 从收集所有class g是为了只抓取该特定 div 中感兴趣的项目 但我只是没有返回或没有打印 每个页面