我需要從一個站點決議資訊,在這個站點上,有 2 個塊,“今天”和“昨天”,它們的類名相同standard-box standard-list。我怎么能只決議第一個連續的塊(在“今日”),不提取“昨天”的通知,如果他們都包含相同的類名?
這是我的代碼:
import requests
url_news = "https://www.123.org/"
response = requests.get(url_news)
soup = BeautifulSoup(response.content, "html.parser")
items = soup.findAll("div", class_="standard-box standard-list")
news_info = []
for item in items:
news_info.append({
"title": item.find("div", class_="newstext",).text,
"link": item.find("a", class_="newsline article").get("href")
})
uj5u.com熱心網友回復:
運行您提供的代碼時,我沒有得到items. 但是,你說你這樣做,所以:
如果您只想獲取“今天”下的資料,您可以使用.find()代替.find_all(),因為.find()只會回傳第一個找到的標簽——即“今天”而不是其他標簽。
所以,而不是:
items = soup.findAll("div", class_="standard-box standard-list")
用:
items = soup.find("div", class_="standard-box standard-list")
此外,為了找到鏈接,我需要訪問的屬性使用tag-name[attribute]。這是作業代碼:
news_info = []
items = soup.find("div", class_="standard-box standard-list")
for item in items:
news_info.append(
{"title": item.find("div", class_="newstext").text, "link": item["href"]}
)
print(news_info)
輸出:
[{'title': 'NIP crack top 3 ranking for the first time in 5 years', 'link': 'https://www.hltv.org/news/32545/nip-crack-top-3-ranking-for-the-first-time-in-5-years'}, {'title': 'Fessor joins Astralis Talent', 'link': 'https://www.hltv.org/news/32544/fessor-joins-astralis-talent'}, {'title': 'Grashog joins AGO', 'link': 'https://www.hltv.org/news/32542/grashog-joins-ago'}, {'title': 'ISSAA parts ways with Eternal Fire', 'link': 'https://www.hltv.org/news/32543/issaa-parts-ways-with-eternal-fire'}, {'title': 'BLAST Premier Fall Showdown Fantasy live', 'link': 'https://www.hltv.org/news/32541/blast-premier-fall-showdown-fantasy-live'}, {'title': 'FURIA win IEM Fall NA, EG claim final Major Legends spot', 'link': 'https://www.hltv.org/news/32540/furia-win-iem-fall-na-eg-claim-final-major-legends-spot'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314398.html
