【问题标题】:BeautifulSoup - Get Text within tag only if a certain string is foundBeautifulSoup - 仅当找到某个字符串时才在标签内获取文本
【发布时间】:2016-10-24 14:39:03
【问题描述】:

我正在尝试从电视节目中抓取一些脚本。我可以使用 BeautifulSoup 和 Requests 获取所需的文本。

import requests
from bs4 import BeautifulSoup

r = requests.get('http://www.example.com')
s = BeautifulSoup(r.text, 'html.parser')

for p in s.find_all('p'):
    print p.text

到目前为止效果很好。但我只想要某个角色的那些段落。说他的名字是“stackoverflow”。文本将是这样的:

答:sdasd sd asda B:sdasds 堆栈溢出:帮助?

所以我只想要 STACKOVERFLOW 所说的内容。不是其余的。

我试过了

s.find_all(text='STACKOVERFLOW') but I get nothing.

这样做的正确方法是什么?一个正确方向的提示将不胜感激。

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    使 部分 文本匹配,使用:

    s.find_all(text=lambda text: text and 'STACKOVERFLOW' in text)
    

    或者:

    import re
    
    s.find_all(text=re.compile('STACKOVERFLOW'))
    

    【讨论】:

      【解决方案2】:

      您可以制作自定义函数以传递给find_all。此函数应接受一个参数(标签)并为符合您条件的标签返回True

      def so_tags(tag):
          '''returns True if the tag has text and 'stackoverflow' is in the text'''
          return (tag.text and "STACKOVERFLOW" in tag.text)
      
      soup.find_all(my_tags)
      

      您还可以创建一个函数工厂,使其更具动态性。

      def user_paragraphs(user):
          '''returns a function'''
          def user_tags(tag):
              '''returns True for tags that have <user> in the text'''
              return (tag.text and user in tag.text)
          return user_tags
      
      for user in user_list:
          user_posts = soup.find_all(user_paragraphs(user))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-12
        • 1970-01-01
        • 2018-02-04
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多