我是一個大二的學生,也是剛接觸python,接觸了爬蟲感覺爬蟲很有趣就爬了爬天涯論壇,中途碰到了很多問題,就想把這些問題分享出來,
都是些簡單的問題,希望大佬們以寬容的眼光來看一個小菜鳥😄,這也是我第一次寫博客,代碼有哪里寫的不好的地方,需要改進的地方希
望大家也可以幫我指出。
用到的包有requests - BeautSoup
我爬的是天涯論壇的財經論壇:‘http://bbs.tianya.cn/list.jsp?item=develop’
它里面的其中的一個帖子的URL:‘http://bbs.tianya.cn/post-develop-2279340-1.shtml’
第一步:定義了三個函數跟一個main函數
def getHtmlText(url): pass def getHtmlList(list,url,main_url):
pass def getHtmlInfo(list,fpath): pass def main(): pass
第一個函數是獲取一個url,通過requests.get()方法,獲取頁面的信息,這是一個獲取url資源的模塊
第二個函數是獲取一個url,調用第一個函數解析財經論壇頁面,獲取到其中的子帖子的url,存放在list中
第三個函數是把list中的url通過for循環一個一個解析頁面,獲取其中我們想要的內容,然后把得到的內容存放在指定的電腦的位置里
main函數里就是調用這幾個函數
第二步:代碼的具體實現
# encoding:utf8
import requestsfrom bs4 import BeautifulSoup
#獲取一個url,通過requests.get()方法,獲取頁面的信息,這是一個獲取url資源的模塊
def getHtmlText(url): try: r = requests.get(url) r.encoding = r.apparent_encoding html = r.text soup = BeautifulSoup(html,'html.parser') return soup except: print("解析網頁出錯")
#獲取一個url,調用第一個函數解析財經論壇頁面,獲取到其中的子帖子的url,存放在list中 def getHtmlList(list,url,main_url): try: soup = getHtmlText(url) managesInfo = soup.find_all('td',attrs={'class':'td-title faceblue'}) for m in range(len(managesInfo)): a = managesInfo[m].find_all('a')//獲取帖子的位置 for i in a: try: href = i.attrs['href'] list.append(main_url+href)//把帖子的url存放在list中 except: continue except: print("獲取網頁失敗")
#把list中的url通過for循環一個一個解析頁面,獲取其中我們想要的內容,然后把得到的內容存放在指定的電腦的位置里 def getHtmlInfo(list,fpath): for i in list: infoDict = {}//初始化存放帖子要獲取的全部信息的字典 authorInfo = []//初始化存放帖子評論的作者的信息的列表 comment = []//初始化存放帖子評論的信息的列表 try: soup = getHtmlText(i) if soup ==""://如果頁面不存在則跳過,繼續獲取 continue Info = soup.find('span',attrs={'style':'font-weight:400;'}) title = Info.text//獲取帖子的標題 infoDict.update({'論壇話題: ':title})//把帖子的標題內容存放到字典中 author = soup.find_all('div',attrs={'class':'atl-info'}) for m in author: authorInfo.append(m.text)//把帖子中的評論的作者的信息存放到列表里 author = soup.find_all('div',attrs={'class':'bbs-content'}) for m in author: comment.append(m.text)//把帖子的評論的信息存放在列表里 for m in range(len(authorInfo)): key = authorInfo[m]+'\n' value = comment[m]+'\n' infoDict[key] = value//把評論的作者的信息跟評論的內容以鍵值對的形式存儲起來 #把獲取到的信息存放在自己指定的位置 with open(fpath,'a',encoding='utf-8')as f: for m in infoDict: f.write(str(m)+'\n') f.write(str(infoDict[m])+'\n') except: continue def main(): main_url = 'http://bbs.tianya.cn' develop_url = 'http://bbs.tianya.cn/list-develop-1.shtml' ulist = [] fpath = r'E:\tianya.txt' getHtmlList(ulist,develop_url,main_url) getHtmlInfo(ulist,fpath) main()//運行main函數
好了,這個代碼就寫完了,我來總結下我在寫這個代碼中遇到的問題。
總結:
這個代碼很簡單,但是其中的一些細節我一開始沒有處理好
在寫第三個函數的時候,把獲取到的信息全部存放在字典中,在調試中發現獲取到的信息有很多重復的,
后來發現是沒有初始化每個列表里的信息。因為是循環存放信息的,讀取完一個帖子的信息之后要把存放
信息的列表初始化,要不會重復輸出之前存入的信息。
