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