生活随笔
收集整理的這篇文章主要介紹了
蚌埠学院官网综合新闻条目抓取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
蚌埠學院綜合新聞
import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
import jsondef get_one_page(url):try:headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'} response = requests.get(url, headers=headers)if response.status_code == 200:return response.textreturn Noneexcept RequestException:return Nonedef page_parser(html):soup = BeautifulSoup(html,'lxml')for td in soup.find_all(name='td',attrs={'height':24}):# 超鏈接href = 'http://www.bbc.edu.cn' + td.find(name='td').a.attrs['href']# 標題title = td.find(name='td').a.font.string# 發布時間postTime = td.find(class_='postTime').stringyield {'href':href,'title':title,'postTime':postTime}def get_pages(url):html = get_one_page(url)soup = BeautifulSoup(html,'lxml')# 獲取總頁碼pages = soup.find(name='a',attrs={'title':'進入尾頁'}).attrs['href']# 將總頁碼提取出來pages = pages.split('/')[8]if pages :return pagesreturn Nonedef write_to_file(content):with open('result.txt','a',encoding='utf-8') as f:f.write(json.dumps(content,ensure_ascii=False) + '\n')def main(num=0):pages = get_pages('http://www.bbc.edu.cn/s/21/t/267/p/22/i/1/list.htm')pages = int(pages)if num:pages=numfor page in range(1,pages):url = 'http://www.bbc.edu.cn/s/21/t/267/p/22/i/'+str(page)+'/list.htm'html = get_one_page(url)for item in page_parser(html):print(item)print('抓取了: '+str(pages)+'頁綜合新聞')if __name__ == '__main__':main(20)
總結
以上是生活随笔為你收集整理的蚌埠学院官网综合新闻条目抓取的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。