BeautifulSoup與正則_簡單爬蟲python3實現
本文的內容python3自我實現程式碼見最下方的程式碼
============以下轉載自:http://blog.csdn.net/w93223010/article/details/20358683===============
本節的內容主要是如何使用一個Python 寫的一個 HTML/XML的解析器——BeautifulSoup,用它將上一節生成的result檔案(就是抓取儲存的網頁原始碼)中所需的內容取出。關於BeautifulSoup的簡介和下載安裝請參考黃聰仁兄的部落格。另附BeautifulSoup的中文文件
先上程式碼:
- from bs4 import BeautifulSoup
- txt='D:\\result1.html'
- f = open(txt, "r")
- html=f.read()
- f.close()
- bs=BeautifulSoup(html)
- gvtitle=bs.find_all('div',attrs={'class':'gvtitle'})
- for title in gvtitle:
- print title.a.text
第1行在程式中引入了BeautifulSoup。
第3至6行是檔案操作,將result1.html檔案中的內容讀取到html變數中。
第8、9行使用BeautifulSoup對html變數進行格式化,並使用find_all方法獲取到所需的資料物件。
第10、11行將獲取的“產品名稱”資訊全部展示出來。
對上段的程式碼進一步解釋:
首先,第一個需求是獲取如圖2-1所示的產品的產品名稱資訊,即“NewFashion Men Slim Fit Cotton V-Neck Short Sleeve Casual T-Shirt Tops”。
![](https://i.iter01.com/images/7b917cc2956acc5b7b6829c9045fbe15adf299bfd6d9beb739590030372d058a.jpg)
圖2-1
其次,觀察result1.html中的原始碼發現,與48個產品相對應,產品名稱全部放在class為gvtitle的48個div內,如圖2-2所示。因此使用find_all方法查詢出所有含class屬性值為gvtitle的div,以列表的形式存入gvtitle變數中。
圖2-2
之後,進一步觀察圖2-2中html檔案的結構,發現“New Fashion Men Slim Fit Cotton V-Neck Short Sleeve Casual T-ShirtTops”這行文字就放在div標籤內的a標籤中,所以在程式碼的第10行用.a.text獲取並展示。上段程式執行結果如圖2-3。
![](https://i.iter01.com/images/a9393668f406924421186d4581fadb8bf1aa11ad0b6757748381ff98b07c70e3.jpg)
圖2-3
接下來修改程式碼,進一步獲取產品的價格資訊。這部分使用了正規表示式,關於正規表示式的知識請參考——正規表示式入門教程
程式碼如下:
- import re
- from bs4 import BeautifulSoup
- def getItems(html):
- pattern = re.compile('\d+.\d+')
- items = re.findall(pattern,html)
- return items
- txt='D:\\result1.html'
- f = open(txt, "r")
- html=f.read()
- f.close()
- bs=BeautifulSoup(html)
- gvtitle=bs.find_all('div',attrs={'class':'gvtitle'})
- for title in gvtitle:
- print title.a.text
- prices=bs.find_all('span',attrs={'class':'amt'})
- for pri in prices:
- result=getItems(str(pri))
- print result
第1行引入正規表示式
第4至7行定義了一個方法,功能是使用正規表示式對BeautifulSoup獲取來的資料進一步篩選。
第19行使用find_all方法獲取到所需的價格。不過觀察result1.html中的原始碼發現,class為amt的span中的資料不如第15行獲取的資料那麼規則,所以在第21行呼叫了getItems方法對資料進一步篩選,獲得價格。
程式執行結果如圖2-4,不過有些產品獲取到了2個價格。這是因為有些產品下有多個子產品,這兩個數值表示的是最低價和最高價,如圖2-5。
為求結果集簡單,就將兩值取平均值作為最終值。
![](https://i.iter01.com/images/566ca9d3a20860856fb65e2a358c39ff20029382ada9b98922317a8a50adbba0.jpg)
圖2-4
圖2-5
修改程式碼,最後如下:
- import re
- import sys
- from bs4 import BeautifulSoup
- def getItems(html):
- pattern = re.compile('\d+.\d+')
- items = re.findall(pattern,html)
- return items
- p=0
- while p<5:
- print ' =='+str(p+1)+'==start=='
- txt='D:\\result'+str(p+1)+'.html'
- fr = open(txt, "r")
- html=fr.read()
- bs=BeautifulSoup(html)
- gvtitle=bs.find_all('div',attrs={'class':'gvtitle'})
- pri_list=[]
- prices=bs.find_all('span',attrs={'class':'amt'})
- for pri in prices:
- res=getItems(str(pri))
- if len(res)==2:
- val=(float(res[0])+float(res[1]))/2
- pri_list.append(val)
- else:
- pri_list.append(res[0])
- j=0
- while j<48:
- try:
- print gvtitle[j].a.text,pri_list[j]
- except UnicodeEncodeError, e:
- for s in gvtitle[j].a.text:
- try:
- sys.stdout.write(s)
- except UnicodeEncodeError, e:
- continue
- sys.stdout.flush()
- print pri_list[j]
- j=j+1
- print ' =='+str(p+1)+'====end=='
- p=p+1
- fr.close()
第31至40行古怪的輸出程式碼是為了刪除掉產品名稱中有時會出現的“™”符號,暫時沒想到更好的辦法,懇請各位童鞋指教。
===============================以下是python3的實現程式碼==================================
#下載網頁原始碼並寫入檔案
import urllib.request
url = "http://www.ebay.com/sch/TShirts-/15687/i.html?Style=Basic%2520Tee&_dcat=15687&Color=Black&_pgn=1"
req = urllib.request.Request(url)
html_open = urllib.request.urlopen(req)
html_data = html_open.read()
html = str(html_data.decode("utf8")) #先read再decode
html = html.replace("\xa0"," ")
html = html.replace("\xa9"," ")
html.encode("gbk") #寫入txt中儘量用gbk編碼
file_name = "f:/test/1.txt"
file_open = open(file_name, "a") #將網頁原始碼寫入1.txt中
file_open.write(html)
file_open.close()
#用bs解析頁面並提取資料資訊_商品名稱
from bs4 import BeautifulSoup
pagepath = "f:/test/pagecode.txt"
pagedata = open(pagepath)
html = pagedata.read()
pagedata.close()
bs = BeautifulSoup(html,"lxml")
gvtitle = bs.find_all("div", attrs={"class":"gvtitle"}) #返回列表形式gvtitle
for title in gvtitle:
print(title.a.text)
#用bs解析頁面並提取資料資訊_商品價格
from bs4 import BeautifulSoup
pagepath = "f:/test/pagecode.txt"
pagedata = open(pagepath)
html = pagedata.read()
pagedata.close()
bs = BeautifulSoup(html,"lxml")
gvtitle = bs.find_all("div", attrs={"class":"gvprices"}) #返回列表形式gvpricesd
for title in gvtitle:
print(title.span.text)
#以上兩端程式碼的彙總實現:用bs解析頁面並提取資料資訊_商品名稱+價格(bs+正則)
import re
from bs4 import BeautifulSoup
pagepath = "f:/test/pagecode.txt"
pagedata = open(pagepath)
html = pagedata.read()
pagedata.close()
def getItems(html):
pattern = re.compile("(\d+.\d*)") #正規表示式
items = re.findall(pattern,html)
if len(items)==2:
ret = (float(items[0])+float(items[1]))/2 #如果價格是一個區間計算平均值
else:
ret = items[0]
return ret
bs=BeautifulSoup(html, "lxml")
gvtitle=bs.find_all('div',attrs={'class':'gvtitle'})
for title in gvtitle:
print (title.a.text )
prices=bs.find_all('span',attrs={'class':'amt'})
for pri in prices:
result=getItems(str(pri))
print (result)
相關文章
- 使用requests+BeautifulSoup的簡單爬蟲練習爬蟲
- Python3爬蟲利器:BeautifulSoup4的安裝Python爬蟲
- 使用正則編寫簡單的爬蟲爬取某網站的圖片爬蟲網站
- Python3 | 簡單爬蟲分析網頁元素Python爬蟲網頁
- Python爬蟲之BeautifulSoupPython爬蟲
- python爬蟲簡單實現逆向JS解密Python爬蟲JS解密
- 【Python爬蟲】正則爬取趕集網Python爬蟲
- Python爬蟲之BeautifulSoup庫Python爬蟲
- python3網路爬蟲開發實戰_Python3 爬蟲實戰Python爬蟲
- java實現一個簡單的爬蟲小程式Java爬蟲
- python 爬蟲 簡單實現百度翻譯Python爬蟲
- 11.18爬蟲學習(BeautifulSoup類)爬蟲
- python 小爬蟲 DrissionPage+BeautifulSoupPython爬蟲
- python3 爬蟲實戰:為爬蟲新增 GUI 影象介面Python爬蟲GUI
- python爬蟲 之 BeautifulSoup庫入門Python爬蟲
- Datawhale-爬蟲-Task3(beautifulsoup)爬蟲
- 寫爬蟲,不會正則怎麼行?爬蟲
- 爬蟲與反爬蟲技術簡介爬蟲
- 簡單的爬蟲程式爬蟲
- python簡單爬蟲(二)Python爬蟲
- 爬蟲系列 | 6、詳解爬蟲中BeautifulSoup4的用法爬蟲
- python如何實現簡單的爬蟲功能?Python學習教程!Python爬蟲
- 誰說爬蟲只能Python?看我用C#快速簡單實現爬蟲開發和演示!爬蟲PythonC#
- 《Python3網路爬蟲開發實戰》教程||爬蟲教程Python爬蟲
- python爬蟲常用庫之BeautifulSoup詳解Python爬蟲
- python爬蟲:爬蟲的簡單介紹及requests模組的簡單使用Python爬蟲
- Golang爬蟲,Go&&正則爬取資料,槓桿的Golang爬蟲
- [Python3網路爬蟲開發實戰] 分散式爬蟲原理Python爬蟲分散式
- go語言實現簡單爬蟲獲取頁面圖片Go爬蟲
- 簡單瞭解python爬蟲Python爬蟲
- 爬蟲,其實本就是這麼簡單爬蟲
- 《Python開發簡單爬蟲》實踐筆記Python爬蟲筆記
- 簡單的爬蟲:爬取網站內容正文與圖片爬蟲網站
- python爬蟲中使用正則match( )方法匹配目標Python爬蟲
- Java培訓教程之使用Jsoup實現簡單的爬蟲技術JavaJS爬蟲
- python爬蟲:使用BeautifulSoup修改網頁內容Python爬蟲網頁
- Java 爬蟲專案實戰之爬蟲簡介Java爬蟲
- Java 的正規表示式與爬蟲Java爬蟲
- Python3網路爬蟲開發實戰Python爬蟲