【问题标题】:Is there a selector that can be used (in Python) to select elements without a tag?是否有可以(在 Python 中)用于选择没有标签的元素的选择器?
【发布时间】:2021-02-14 23:03:01
【问题描述】:
<div id="some id" class="some class">
    <table id="some other id" class="a different class">...</table>
    
        
        I want this text,


    <br>
    
        this text,


    <br>


        along with this text


    </div>

我正在尝试使用 Python 来网页抓取具有类似代码的多个页面,如上所示。我尝试使用基本的 Python CSS 选择器来获取文本,但无法解决。我主要想知道是否有一个选择器可以通过 Beautiful Soup select() 方法传递,该方法选择&lt;div&gt; 中但不在&lt;table&gt; 中的元素。我尝试选择&lt;br&gt;(不知道它的作用),但没有成功。

我对 HMTL 知之甚少,因此对于上述代码示例中的任何错误或混淆,我深表歉意。

【问题讨论】:

    标签: web-scraping css-selectors python-3.6


    【解决方案1】:

    简单地删除子表标签可能更容易

    from bs4 import BeautifulSoup as bs
    
    html = '''
    <div id="some id" class="some class">
        <table id="some other id" class="a different class">not this</table>
    
    
            I want this text,
    
    
        <br>
    
            this text,
    
    
        <br>
    
    
            along with this text
    
    
        </div>
    '''
    
    soup = bs(html, 'lxml')
    soup.select_one('[id="some other id"]').extract()
    print(soup.select_one('[id="some id"]').text)
    

    【讨论】:

      【解决方案2】:

      解决方案实际上非常简单。经过实验,发现可以使用下面的代码来获取上面HTML的文本。

      import requests, bs4
      
      #Create a BeautifulSoup Object
      url = 'https://url.thisisthewebsitecontainingthehtml.com'
      res = requests.get(url)
      res.raise_for_status()
      soup = bs4.BeautifulSoup(res.text)
      
      #Create a list containing all elements with the tag <div>
      divElems = soup.select('div[id="some id"]')
      #Create an empty list to add the text
      trueText = []
      for i in divElems:
          text = list(i)
          trueText.append((text[-5].strip(), text[-3].strip(), text[-1].strip()))
      

      Python 的 list() 函数将选定的 HTML 划分为单独的“块”——&lt;table&gt; 标记下的所有内容、文本的第一位、&lt;br&gt; 标记、文本的下一位、另一个 &lt;br&gt; 标记,以及最后一段文字。由于我们只想要包含文本的“块”,因此我们将text 列表的“-1”、“-3”和“-5”元素添加到我们的trueText 列表中。

      执行此代码将创建一个列表,trueText,其中包含来自上述 HTML 的所需文本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-16
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        • 1970-01-01
        • 2016-07-21
        • 1970-01-01
        相关资源
        最近更新 更多