以下是一個用于爬取某個網(wǎng)站的新聞標題和鏈接,并將結(jié)果保存到文本文件中的Python爬蟲案例: import requests from bs4 import BeautifulSoup # 網(wǎng)站鏈接 url = 'https://www.example.com/news/' # 發(fā)送請求 response = requests.get(url) # 解析HTML soup = BeautifulSoup(response.text, 'html.parser') # 獲取新聞標題和鏈接 news_list = [] for news in soup.find_all('div', class_='news-item'): title = news.find('a').text.strip() link = news.find('a')['href'] news_list.append((title, link)) # 將結(jié)果保存到文本文件 with open('news.txt', 'w', encoding='utf-8') as f: for title, link in news_list: f.write(f'{title}\t{link}\n')
說明:
1. 使用requests庫發(fā)送GET請求獲取網(wǎng)頁內(nèi)容。
2. 使用BeautifulSoup庫解析HTML文檔。
3. 使用find_all()方法查找所有class屬性為’news-item’的div標簽,然后分別從中獲取新聞標題和鏈接。
4. 將結(jié)果保存到文本文件中,每條新聞標題和鏈接之間用制表符分隔,每條新聞之間用換行符分隔。
未經(jīng)允許不得轉(zhuǎn)載:445IT之家 » 一個python爬蟲小案例(超簡單)