【爬蟲】002 python3 +beautifulsoup4 +requests 爬取靜態頁面
阿新 • • 發佈:2018-08-07
bgcolor img err 預覽 政府 bold 技術 貴的 頁面元素
實驗環境: win7 python3.5 bs4 0.0.1 requests 2.19
實驗日期:2018-08-07
爬取網站:http://www.xhsd.cn/
現在的網站大多有復雜的交互,地方政府的網站又太簡單,體現不出bs4的解析過程; http://www.xhsd.cn/ 這個網站,還算現代,很可貴的是它還是直接在服務端返回的,客戶端沒有渲染;
2018-08-07 它的預覽是這樣的(爬取之前,先通過chrome瀏覽器 檢查 頁面元素,了解頁面html構造)
希望抓取 推薦圖書 新書速遞 考試用書等
python 抓取代碼
import requests import bs4 import pandas as pd import re url="""http://www.xhsd.cn/""" r=requests.get(url) html=r.text soup=bs4.BeautifulSoup(html,‘lxml‘) tables=soup.find_all(‘table‘,bgcolor="#ffffff") def etr(tb): content={} arr=list(filter(lambda x:len(str(x))>2,tb.children)) tr1=arr[0] tr2=arr[1] label=next(tr1.stripped_strings) content[‘label‘]=label print(label) a_s=tr2.find_all(‘a‘,title=True) cs=[] for a in a_s: try: cts=list(a.stripped_strings) #print(cts) book,auth,price_now,price_before=cts img=a.find(‘img‘)[‘src‘] tmp={"book":book,"auth":auth,"price_now":price_now,"price_before":price_before,"image":img} cs.append(tmp) except: continue content["contents"]=cs return content tables=tables dfs=[] for tb in tables: content=etr(tb) df_tmp=pd.DataFrame(data=content[‘contents‘]) df_tmp[‘label‘]=content[‘label‘] dfs.append(df_tmp) df=pd.concat(dfs,ignore_index=True)
圖片的處理
爬取下來的數據中,有df[‘image‘] 以http://www.xhsd.cn//upload/2017/7/1500881045493.jpg 為例
[‘http://www.xhsd.cn//upload/2017/7/1500881045493.jpg‘, ‘http://www.xhsd.cn//upload/20160701\\9787201077642.JPG‘, ‘http://www.xhsd.cn//upload/20160621\\9787201088945.JPG‘, ‘http://www.xhsd.cn//upload/2017/6/1498807359861.jpg‘]
下一張博客講下載圖片 和簡單處理
【爬蟲】002 python3 +beautifulsoup4 +requests 爬取靜態頁面