python抓取簡單網頁數據的小實例

抓取網頁數據的思路有好多種,通常有:直接代碼請求http、模擬瀏覽器請求數據(一般須要登陸驗證)、控制瀏覽器實現數據抓取等。這篇不考慮複雜狀況,放一個讀取簡單網頁數據的小例子:html

目標數據

將ittf網站上這個頁面上全部這些選手的超連接保存下來。
圖片描述python

數據請求

真的很喜歡符合人類思惟的庫,好比requests,若是是要直接拿網頁文本,一句話搞定:瀏覽器

doc = requests.get(url).text

解析html得到數據

以beautifulsoup爲例,包含獲取標籤、連接,以及根據html層次結構遍歷等方法。參考見這裏。下面這個片斷,從ittf網站上獲取指定頁面上指定位置的連接。app

url = 'http://www.ittf.com/ittf_ranking/WR_Table_3_A2.asp?Age_category_1=&Age_category_2=&Age_category_3=&Age_category_4=&Age_category_5=&Category=100W&Cont=&Country=&Gender=W&Month1=4&Year1=2015&s_Player_Name=&Formv_WR_Table_3_Page='+str(page)
doc = requests.get(url).text
soup = BeautifulSoup(doc)
atags = soup.find_all('a')
rank_link_pre = 'http://www.ittf.com/ittf_ranking/'

mlfile = open(linkfile,'a')
for atag in atags:
    #print atag
    if atag!=None and atag.get('href') != None:
        if "WR_Table_3_A2_Details.asp" in atag['href']:
            link = rank_link_pre + atag['href']
            links.append(link)
            mlfile.write(link+'\n')
            print 'fetch link: '+link
mlfile.close()
相關文章
相關標籤/搜索