【问题标题】:How to extract text based on a condition in python如何根据python中的条件提取文本
【发布时间】:2020-11-13 15:37:17
【问题描述】:

我的汤数据如下所示。

<a href="/title/tt0110912/" title="Quentin Tarantino">
Pulp Fiction
</a>

<a href="/title/tt0137523/" title="David Fincher">
Fight Club
</a>

<a href="blablabla" title="Yet to Release">
Yet to Release
</a>

<a href="something" title="Movies">
Coming soon
</a>

我需要来自a 标签的文本数据,可能是href=/title/*wildcharacter*

我的可能有点像这样。

titles = []

for a in soup.find_all("a",href=True):
    if a.text:
        titles.append(a.text.replace('\n'," "))
print(titles)

但在这种情况下,我会从所有 a 标记中获取文本。我只需要href 具有"/title/***" 的文本。

【问题讨论】:

    标签: python pandas beautifulsoup


    【解决方案1】:

    1.) 要获取所有&lt;a&gt; 标签,其中href="/title/" 开头,您可以使用CSS 选择器a[href^="/title/"]

    2.) 要去除标签内的所有文本,您可以使用.get_text() 和参数strip=True

    soup = BeautifulSoup(html_text, 'html.parser')
    
    out = [a.get_text(strip=True) for a in soup.select('a[href^="/title/"]')]
    print(out)
    

    打印:

    ['Pulp Fiction', 'Fight Club']
    

    【讨论】:

      【解决方案2】:

      我猜你想要这样:

      from bs4 import BeautifulSoup
      
      html = '''<a href="/title/tt0110912/" title="Quentin Tarantino">
      Pulp Fiction
      </a>
      
      <a href="/title/tt0137523/" title="David Fincher">
      Fight Club
      </a>
      
      <a href="blablabla" title="Yet to Release">
      Yet to Release
      </a>
      
      <a href="something" title="Movies">
      Coming soon
      </a>
      '''
      
      soup = BeautifulSoup(html, 'html.parser')
      
      titles = []
      
      for a in soup.select('a[href*="/title/"]',href=True):
          if a.text:
              titles.append(a.text.replace('\n'," "))
      print(titles)
      

      输出:

      [' Pulp Fiction ', ' Fight Club ']
      

      【讨论】:

        【解决方案3】:

        您可以使用正则表达式来搜索属性的内容(在本例中为 href)。

        更多详情请参考这个答案:https://stackoverflow.com/a/47091570/1426630

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-10-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多