题目要求:你需要爬取的是网上书店Books to ScrapeTravel这类书中,所有书的书名、评分、价格三种信息,并且打印提取到的信息。
网页URL:
1 #3、书店寻宝(二) 2 # 题目要求:你需要爬取的是网上书店Books to ScrapeTravel这类书中,所有书的书名、评分、价格三种信息,并且打印提取到的信息。 3 # 网页URL:http://books.toscrape.com/catalogue/category/books/travel_2/index.html 4 5 import requests 6 from bs4 import BeautifulSoup 7 res = requests.get('http://books.toscrape.com/catalogue/category/books/travel_2/index.html') 8 html = res.text 9 soup = BeautifulSoup(html,'html.parser')10 items = soup.find_all('article',class_='product_pod')11 for item in items:12 print(item.find('h3').find('a')['title']+'\t'+item.find('p')['class'][1],'\t',item.find('p',class_='price_color').text)13 # print(item.find('h3').find('a')['title'])14 # print(item.find('p')['class'][1])15 # print(item.find('p',class_='price_color').text)16 17 18 '''19 执行结果如下:20 It's Only the Himalayas Two £45.1721 Full Moon over Noahâs Ark: An Odyssey to Mount Ararat and Beyond Four £49.4322 See America: A Celebration of Our National Parks & Treasured Sites Three £48.8723 Vagabonding: An Uncommon Guide to the Art of Long-Term World Travel Two £36.9424 Under the Tuscan Sun Three £37.3325 A Summer In Europe Two £44.3426 The Great Railway Bazaar One £30.5427 A Year in Provence (Provence #1) Four £56.8828 The Road to Little Dribbling: Adventures of an American in Britain (Notes From a Small Island #2) One £23.2129 Neither Here nor There: Travels in Europe Three £38.9530 1,000 Places to See Before You Die Five £26.0831 '''32 33 '''34 老师的代码35 36 import requests37 from bs4 import BeautifulSoup38 39 res_bookstore = requests.get('http://books.toscrape.com/catalogue/category/books/travel_2/index.html')40 bs_bookstore = BeautifulSoup(res_bookstore.text,'html.parser')41 list_books = bs_bookstore.find_all(class_='product_pod')42 for tag_books in list_books:43 # 找到a标签需要提取两次44 tag_name = tag_books.find('h3').find('a')45 # 这个p标签的class属性有两种:"star-rating",以及具体的几星比如"Two"。我们选择所有书都有的class属性:"star-rating"46 list_star = tag_books.find('p',class_="star-rating")47 # 价格比较好找,根据属性提取,或者标签与属性一起都可以48 tag_price = tag_books.find('p',class_="price_color")49 # 这里用到了tag['属性名']提取属性值50 print(tag_name['title'])51 # 同样是用属性名提取属性值52 print('star-rating:',list_star['class'][1])53 # 用list_star['class']提取出来之后是一个由两个值组成的列表,如:"['star-rating', 'Two']",我们最终要提取的是这个列表的第1个值:"Two"。54 # 为什么是列表呢?因为这里的class属性有两个值。其实,在这个过程中,我们是使用class属性的第一个值提取出了第二个值。55 # 打印的时候,我加上了换行,为了让数据更加清晰地分隔开,当然你也可以不加。56 print('Price:',tag_price.text, end='\n'+'------'+'\n')57 '''
items中每个Tag的内容如下
12 6 13 It's Only the14 Himalayas
151629£45.17
1718 19 20 21 In stock22 23 24
25 28