美文网首页
案例25:tag通过属性名提取属性值

案例25:tag通过属性名提取属性值

作者: Iphone60Plus | 来源:发表于2020-06-26 13:38 被阅读0次
#考查beautiful中find find_all 及 tag['属性']
import requests
from bs4 import BeautifulSoup

url = 'http://books.toscrape.com/catalogue/category/books/travel_2/index.html'
res = requests.get(url)
res_text = res.text
bs = BeautifulSoup(res_text,'html.parser')

items = bs.find_all(class_="product_pod")
for item in items:
    name = item.find('h3').find('a')
    star = item.find('p',class_="star-rating")
    #源代码中<p class="star-rating Two">class有两个属性值,选择所有书都有的属性值star-rating,
    money = item.find('p',class_="price_color")
    print(name['title'])
    #通过tag['属性名']来提取属性值
    print('star:',star['class'][1])
    #同样是用属性名来提取属性值
    #用star['class']提取出来之后是一个由两个值组成的列表,如:"['star-rating', 'Two']",我们最终要提取的是这个列表的第1个值:"Two"。
    #为什么是列表呢?因为这里的class属性有两个值。其实,在这个过程中,我们是使用class属性的第一个值提取出了第二个值。
    print('money:',money.text,end='\n'+'--------'+'\n')

相关文章

网友评论

      本文标题:案例25:tag通过属性名提取属性值

      本文链接:https://www.haomeiwen.com/subject/rkxufktx.html