本文實例講述了Python基于BeautifulSoup和requests實現的爬蟲功能。分享給大家供大家參考,具體如下:
爬取的目標網頁:http://www.qianlima.com/zb/area_305/
這是一個招投標網站,我們使用python腳本爬取紅框中的信息,包括鏈接網址、鏈接名稱、時間等三項內容。
使用到的Python庫:BeautifulSoup、requests
代碼如下:
# -*- coding:utf-8 -*-import requestsfrom bs4 import BeautifulSoupurl = 'http://www.qianlima.com/zb/area_305/'user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'headers = { 'User-Agent' : user_agent}r = requests.get(url,headers=headers)#連接content = r.text#獲取內容,自動轉碼unicodesoup = BeautifulSoup(content,"lxml")tags1 = soup.select('div .shixian_zhaobiao')tag1 = tags1[0]tag2 = tag1.find(name = 'dl')tags2 = tag2.find_all(name = 'a')tags3 = tag2.find_all(name = 'dd')for tag in tags2: print tag.get('href') print tag.string print tag.next_element.next_element.string
運行結果如下
更多關于Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python正則表達式用法總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答