python网络数据采集练习2

基于书籍《python网络数据采集》([美]Ryan Mitchell)

第二章2.2.3

子标签,兄弟标签,父标签。

1.处理子标签(两种,第一种children标签,另一种descendants标签,children仅是下一级,descendants则是父标签下所有级别。

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen ("http://www.pythonscraping.com/pages/page3.html");
bsObj = BeautifulSoup(html,"html.parser")

#children只是下一级,descendants是所有级别后代。
for child in bsObj.find("table",{"id":"giftList"}).children:
	print(child)


2.处理兄弟标签

对象不能把自己当作兄弟标签,且分为next_siblings和previous_siblings从前和从后两种找兄弟函数。

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"html.parser")

#找到一组兄弟从第一个开始用next_siblings,从最后一个则用previous_sibings
for sibling in bsObj.find("table",{"id":"giftList"}).tr.next_siblings:
	print(sibling)


3.处理父标签

原理同上

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"html.parser")

print(bsObj.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text())
#这里<td>是src:../img/gifts/img1.jpg的父类,先parent找到这个父类在找钱一个具有价格信息的兄弟在输出信息




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值