【问题标题】:Python Beautiful Soup crawl text dataPython Beautiful Soup 爬取文本数据
【发布时间】:2013-06-18 00:06:43
【问题描述】:

我是 python 的新手,我正在尝试使用 Python 中的 beautifulSoup 从网站上抓取一些文本 cmets。部分html结构如下,

<div style="1st level">
    <div style="2nd level">Here is text 1</div>
    <div style="2nd level">Here is text 2</div>
    <div style="2nd level">Here is text 3</div>
    <div style="2nd level">Here is text 4</div>
    Here is text 5 and this is the part I want to get.
<div>

所以文本 1,2,3,4 位于第 2 级,我不需要这些文本。我只想获取位于结构第一级的文本 5。我的部分代码如下:

reviews=soup.find('div',style="1st level")
reviews=reviews.text
print reviews

但是后来我得到了从文本 1 到文本 5 的所有内容。有没有一种简单的方法可以定位到第 1 级并且只获取文本 5?

【问题讨论】:

  • 我们几乎肯定需要相关网站的 html 源代码来帮助您解决这个问题。
  • 我去修复你的问题格式,发现有一些 html 源代码(虽然还不够)。请编辑您的帖子,插入实际的 html 源代码,并确保格式正确。
  • 你确定那些style= 不应该是class= 吗?

标签: python beautifulsoup


【解决方案1】:

不确定这些方法是否最好,但请尝试一下:

from bs4 import BeautifulSoup as soup
from collections import deque


input = """<div style="1st level">
    <div style="2nd level">Here is text 1</div>
    <div style="2nd level">Here is text 2</div>
    <div style="2nd level">Here is text 3</div>
    <div style="2nd level">Here is text 4</div>
    Here is text 5 and this is the part I want to get.
<div>"""

web_soup = soup(input)
reviews = web_soup.find('div', style="1st level")

print reviews.contents[-2]
print deque(reviews.strings, maxlen=1).pop()

两个打印件:

Here is text 5 and this is the part I want to get.

仅供参考,我已使用 dequestrings 生成器中获取最后一个元素。

而且,仅供参考,通过使用text(),lxml + xpath 会更轻松地完成这项工作。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2015-09-08
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多