python3 爬「斗圖啦」
- 2020 年 1 月 6 日
- 筆記
接觸了一個多月的python,終於可以小小露一手了。手法之拙略就不得不恭維了,哈哈,
環境win7系統,Python3.6,Pycharm2017社區版,還有Google瀏覽器(官網均可下載)
http://www.doutula.com
需要的模組requests, lxml, BeautifulSoup,
import requests import lxml from bs4 import BeautifulSoup
說明一下,下載很多網站都有了反爬機制,所以道高一尺,魔高一丈了,我們模擬瀏覽器去訪問網站,
也就是獲得
User-Agent:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36
方法:隨便打開網頁 F12 –Network –F5 –Headers — User-Agent

程式碼來了
start_url = "http://www.doutula.com/arcticle/list/?page=1" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'} start_html = requests.get(url=url, headers=headers).content #print(start_html) soup = BeautifulSoup(start_html,'lxml') ##lxml 解析網頁的 all_a = soup.find_all('a',attrs={'class':'list-group-item'}) for a in all_a: #title = a.h4.get_text() url = a['href'] #print(title,url)

每一套「斗圖」對應一個 a 標籤,所以直接find_all('a',attrs={'class':'list-group-item'}),謝謝站長布局如此規律。
注意這是上面程式碼的繼續,所以注意 縮進
img_html = requests.get(url,headers=header).text img_soup = lxml.etree.HTML(img_html) ##列印源碼,自動修正html img_items = img_soup.xpath('//div[@class="artile_des"]') for item in img_items: imgurl_list = item.xpath('table/tbody/tr/td/a/img/@src')[0] ##[0]取list的第一個元素 print("正在下載"+imgurl_list) imgcontent = requests.get(imgurl_list).content ##換成text會報錯no 'str' with open('doutu/%s' % imgurl_list.split('/')[-1],'wb') as f: ##doutu是文件夾,需要自己提前創建 f.write(imgcontent)

然後就有你要的圖了,一個一個,據說還可以多執行緒下載,當然需要另一個模組(threading)了的,
下次見