【问题标题】:Get text between <span> tag that is inside another <span> tag获取另一个 <span> 标签内的 <span> 标签之间的文本
【发布时间】:2019-01-07 14:45:13
【问题描述】:

我当前获取所需内容的代码如下所示:

#BeautifulSoup
textContent = []
headline = soup.find('a', attrs={"class":"title"}).text
review = soup.find('div', attrs={"class":"text show-more__control"}).text
rating = soup.find('div', attrs={"class":"rating-other-user-rating"})

textContent.append(headline)
print(headline)
textContent.append(review)
print(review)
textContent.append(rating)
print(rating)

我得到了评论的标题和文本,但没有得到评级,因为此信息与其他信息位于不同的“标签系统”中。在 html 代码中,它看起来像这样:

<span class="rating-other-user-rating">
        <svg class="ipl-icon ipl-star-icon  " xmlns="http://www.w3.org/2000/svg" fill="#000000" height="24" viewBox="0 0 24 24" width="24">
            <path d="M0 0h24v24H0z" fill="none"></path>
            <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"></path>
            <path d="M0 0h24v24H0z" fill="none"></path>
        </svg>
            <span>6</span><span class="point-scale">/10</span>
        </span>

我想得到的信息是“6”。显然,我不能只使用“soup.find.---.text(),因为它是一个无对象。

感谢您的帮助!

【问题讨论】:

  • 它没有返回任何内容,因为你让它在寻找 &lt;div&gt;,而不是 span
  • 从寻找span 元素而不是div 开始。如果您使用的是 BeautifulSoup 4.7 或更高版本,请使用 CSS 选择器:.select_one('span.rating-other-user-rating span')
  • @MartijnPieters 在早期版本的 BS4 中也能正常工作——尽管那个汤筛看起来很棒——感谢你在推特上发布的消息——这已经出现在我的“当我有时间玩的东西”上:)
  • @JonClements:可能,但我现在懒得再次找出旧的选择器引擎到底支持什么。它以奇怪的方式被破坏和限制,有了 soupsieve,我们可以继续前进,改用像样的引擎。
  • @MartijnPieters soup.select_one('span.rating-other-user-rating &gt; span').text 在这里工作得很好......我可能需要在某个时候正确检查soupsieve项目,因为如果它也做了一些scrapy所做的事情来扩展它会很好使用 lxml 的 cssselectors... 能够执行以下操作:soup.select('span.rating-other-user-rating &gt; span::attr(text)') 会很棒。

标签: html python-3.x beautifulsoup web-crawler


【解决方案1】:

1) 将'div' 更改为'span'

2)

  • a) 那么你可以得到文本
  • b) 去掉空格,得到6/10
  • c) 在'/' 处拆分
  • d) 在索引[0] 处获取该列表中的元素

替换:

rating = soup.find('div', attrs={"class":"rating-other-user-rating"})

与:

rating = soup.find('span', attrs={"class":"rating-other-user-rating"}).text.strip().split('/')[0]

输出:

print (rating)
6

【讨论】:

  • 谢谢!其实我只是复制了错误的代码。我的代码中有“跨度”,但仍然不知道如何继续并获得此输出
  • @Narallio 请注意,您也可以在显示的 HTML sn-p 上使用 soup.select_one('span.rating-other-user-rating &gt; span').text...
  • 谢谢!该解决方案实际上似乎更容易更好地记住以后。因为我是 BeautifulSoup 的新手,所以以前没有使用过“select_one”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-11
  • 2019-12-23
  • 2021-07-26
  • 1970-01-01
相关资源
最近更新 更多