一、介紹
爬取貓眼電影的翻版勺卢,練練手的同時也有新發(fā)現(xiàn)
二裙犹、流程
用瀏覽器打開糗事百科尽狠,分析站點
抓取單頁內(nèi)容
利用Requests請求目標(biāo)站點,得到單個網(wǎng)頁HTML代碼叶圃,返回結(jié)果正則表達(dá)式分析
根據(jù)HTML代碼分析得到的用戶名稱袄膏、段子文本、點贊人數(shù)掺冠、評論人數(shù)等信息
1.png
保存至文件
通過文件的形式將結(jié)果保存沉馆,每一部電影一個結(jié)果一行Json字符串開啟循環(huán)及多線程
對多頁內(nèi)容遍歷,開啟多線程提高抓取速度 德崭,這里為了保證獲取文本信息格式的一致性斥黑,我就沒有不用多線程了
三、代碼
import requests
import re
import json
from requests.exceptions import RequestException
import time
def get_one_page(url):
use_agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'
Headers={'User-Agent':use_agent}
#如果不加報頭直接抓取源代碼似乎會報錯眉厨,所以我偽裝了一下锌奴,打開chrome進(jìn)入糗事百科,再右鍵打開檢查->network->request headers憾股,把User-Agent復(fù)制了
try:
response=requests.get(url,headers=Headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
def parse_one_page(html):
pattern = re.compile('<h2>(.*?)</h2>.*?<span>(.*?)</span>.*?<i cla'
+ 'ss="number">(.*?)</i> (.*?)</span>.*?<i class="number">(.*?)</i>(.*?)</a>', re.S)
items=re.findall(pattern,str(html)) #這里要對html用str()函數(shù)鹿蜀,不然會報錯 TypeError: expected string or bytes-like object
#print(items)
for item in items:
yield {
'name':item[0].strip(),
'text':item[1].replace("<br/>",",").strip(), #替換掉網(wǎng)頁中的<br/>轉(zhuǎn)行標(biāo)簽,去掉換行符
'vote':(item[2]+item[3]),
'comments':(item[4]+item[5]).strip()
}
def write_to_file(content):
with open('result.text','a',encoding='utf-8') as f:
f.write(json.dumps(content,ensure_ascii=False)+'\n')
f.close()
def main():
for i in range(1, 14):
url = 'https://www.qiushibaike.com/hot/page/' + str(i) #把循環(huán)放在這里服球,不要弄在main()里
print('當(dāng)前處理頁數(shù):',i)
get_one_page(url)
html=get_one_page(url)
for item in parse_one_page(html):
print(item)
write_to_file(item)
time.sleep(3)
if __name__=='__main__':
main() #這是標(biāo)準(zhǔn)的main格式
四耻姥、最后得到的text文件
2.png
五、總結(jié)
1.磕磕碰碰的做出來有咨,很開心
2.在這里非常感謝皮皮哥琐簇、風(fēng)、Luffy等大佬的悉心指導(dǎo)