本文實例講述了Python3實現爬取簡書首頁文章標題和文章鏈接的方法。分享給大家供大家參考,具體如下:
from urllib import requestfrom bs4 import BeautifulSoup #Beautiful Soup是一個可以從HTML或XML文件中提取結構化數據的Python庫#構造頭文件,模擬瀏覽器訪問url="http://www.jianshu.com"headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}page = request.Request(url,headers=headers)page_info = request.urlopen(page).read().decode('utf-8')#打開Url,獲取HttpResponse返回對象并讀取其ResposneBody# 將獲取到的內容轉換成BeautifulSoup格式,并將html.parser作為解析器soup = BeautifulSoup(page_info, 'html.parser')# 以格式化的形式打印html#print(soup.prettify())titles = soup.find_all('a', 'title')# 查找所有a標簽中class='title'的語句'''''# 打印查找到的每一個a標簽的string和文章鏈接 for title in titles: print(title.string) print("http://www.jianshu.com" + title.get('href'))'''#open()是讀寫文件的函數,with語句會自動close()已打開文件with open(r"D:/articles.txt","w") as file: #在磁盤以只寫的方式打開/創建一個名為 articles 的txt文件 for title in titles: file.write(title.string+'/n') file.write("http://www.jianshu.com" + title.get('href')+'/n/n')本機測試運行結果如下:
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答