python - 嵌套标签网络抓取python

标签 python html web-scraping beautifulsoup

我正在从特定网站抓取固定内容。内容位于嵌套的 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'

任何人都可以给我一些想法来检索 span 中的 div 的内容。谢谢。 我用的是python2.7

最佳答案

您似乎想从 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

关于python - 嵌套标签网络抓取python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22777187/

相关文章:

python - JSON 类型错误 : expected string or buffer

javascript - PHP AJAX 实时搜索页面定位同一页面而不是新窗口

python - 如何使用 python+beautifulsoup 抓取标签之外的项目

css - 为什么我的按钮左侧的下拉元素不在下方?

javascript - javascript 的日期格式

python - 网页抓取打印换行符

java - 代理无法在 webDriver 中的 chromeOptions 中与 Java 中的 selenium 一起工作

Python 和 Regex 将书面数字转换为数字

python - 2D numpy argsort 索引在原始矩阵中使用时返回 3D

python - 无法在mysql数据库中添加列表列表