【问题标题】:Nested tags web scraping python嵌套标签网页抓取 python
【发布时间】:2014-05-11 17:07:42
【问题描述】:

我正在从特定网站抓取固定内容。内容位于嵌套的 div 中,如下所示:

<div class="table-info">
  <div>
    <span>Time</span>
        <div class="overflow-hidden">
            <strong>Full</strong>
        </div>
  </div>
  <div>
    <span>Branch</span>
        <div class="overflow-hidden">
            <strong>IT</strong>
        </div>
  </div>
  <div>
    <span>Type</span>
        <div class="overflow-hidden">
            <strong>Standard</strong>
        </div>
  </div>
  <div>
    <span>contact</span>
        <div class="overflow-hidden">
            <strong>my location</strong>
        </div>
 </div>
</div>

我想用字符串值 Branch 检索 span 内 div 'overflow-hidden' 中唯一的 strong 内容。我使用的代码是:

from bs4 import BeautifulSoup
import urllib2 
url = urllib2.urlopen("https://www.xyz.com")
content = url.read()
soup = BeautifulSoup(content)
type = soup.find('div',attrs={"class":"table-info"}).findAll('span')
print type

我已经抓取了主 div 'table-info' 中的所有 span 内容,以便我可以使用条件语句来检索所需的内容。但是,如果我尝试将跨度内的 div 内容废弃为:

type = soup.find('div',attrs={"class":"table-info"}).findAll('span').find('div')
print type

我得到错误:

AttributeError: 'list' object has no attribute 'find'

谁能给我一些想法来检索跨度中 div 的内容。谢谢你。 我正在使用python2.7

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    您似乎想从 div-"table-info" 中的第二个 div 获取内容。但是,您正在尝试使用与您尝试访问的内容无关的标签来获取它。

     type = soup.find('div',attrs={"class":"table-info"}).findAll('span').find('div') 
    

    返回错误,因为它是空的。

    最好试试这个:

    from bs4 import BeautifulSoup
    import urllib2 
    url = urllib2.urlopen("https://www.xyz.com")
    content = url.read()
    soup = BeautifulSoup(content)
    type = soup.find('div',attrs={"class":"table-info"}).findAll('div')
    print type[2].find('strong').string
    

    【讨论】:

    • 谢谢,代码有效。我想我在解决问题时采用了一种完全错误的方法。
    【解决方案2】:

    findAll 返回 BS 元素列表,find 是在 BS 对象上定义的,而不是 BS 对象列表,因此出现错误。您的代码的初始部分很好, 改为这样做:

    from bs4 import BeautifulSoup
    import urllib2 
    
    url = urllib2.urlopen("https://www.xyz.com")
    content = url.read()
    soup = BeautifulSoup(content)
    
    table = soup.find('div',attrs={"class":"table-info"})
    spans = table.findAll('span')
    branch_span = span[1]
    # Do you manipulation with the branch_span
    

    from bs4 import BeautifulSoup
    import urllib2 
    
    url = urllib2.urlopen("https://www.xyz.com")
    content = url.read()
    soup = BeautifulSoup(content)
    
    table = soup.find('div',attrs={"class":"table-info"})
    spans = table.findAll('span')
    
    for span in spans:
        if span.text.lower() == 'branch':
            # Do your manipulation
    

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2021-10-08
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      相关资源
      最近更新 更多