python新手,我一直在使用這段代碼來獲取類名作為我的csv的文本,但不能只提取第一個。你知道怎么做嗎?
for x in book_url_soup.findAll('p', class_="star-rating"):
for k, v in x.attrs.items():
review = v[1]
reviews.append(review)
del reviews[1]
print(review)
網址是:http: //books.toscrape.com/catalogue/its-only-the-himalayas_981/index.html
輸出是:
Two
Two
One
One
Three
Five
Five
我只需要第一個輸出,不知道如何防止代碼從共享相同類名的頁面下方獲得“星級”。
uj5u.com熱心網友回復:
取而代之的是find_all(),ResultSet您可以使用find()或select_one()僅選擇第一次出現的元素并從類名串列中選擇最后一個索引:
soup.find('p', class_='star-rating').get('class')[-1]
或與css selector
soup.select_one('p.star-rating').get('class')[-1]
在較新的代碼中,也避免使用舊語法findAll(),而是使用find_all()- 更多時間檢查檔案
例子
from bs4 import BeautifulSoup
import requests
url = 'http://books.toscrape.com/catalogue/its-only-the-himalayas_981/index.html'
page = requests.get(url).text
soup = BeautifulSoup(page)
soup.find('p', class_='star-rating').get('class')[-1]
輸出
Two
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/492892.html
