Python實戰(zhàn)

本章學(xué)習(xí)代碼收錄在

GitHub - jiajia154569836/Python: python實戰(zhàn)筆記

注意:

1.需要先安裝python

2.需安裝依賴?yán)簆ython -m pip install requests

3.踩到的坑

win10岭佳,python3.5 安裝scrapy - python菜鳥 - 博客園

scrapy寫爬蟲是出現(xiàn)no module named win32api錯誤 - 不活在夢想里 - 博客園

0.彩蛋

使用Python畫小豬佩奇(Python內(nèi)置的turtle庫) - CSDN博客

1.爬取酷狗top500

設(shè)計方案:

1.根據(jù)requests獲取html

2.根據(jù)BeautifulSoup解析html

3.找到需要查找的文本的class使用選擇器

4.存入Mongo,time的設(shè)置是為了降低爬去的速度防止存入與爬取不對等

因為我沒有安裝Mongo其中部分代碼注釋(直接打印到控制臺了)

代碼如下:

import time

import requests

from bs4import BeautifulSoup

from pymongoimport MongoClient

#client = MongoClient()? # mongodb server

#songs = client.kugou_db.songs # song collection

headers= {

? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'

}

def get_info(url):

? ? '''獲取酷狗音樂TOP500信息'''

? ? wb_data= requests.get(url, headers=headers)

? ? soup= BeautifulSoup(wb_data.text, 'lxml')

? ? ranks= soup.select('.pc_temp_num')? # 排名list

? ? titles= soup.select('.pc_temp_songlist > ul > li > a')? # 名稱list

? ? song_times= soup.select('.pc_temp_time')? # 歌曲時長list

? ? for rank, title, song_timein zip(ranks, titles, song_times):

? ? ? ? data= {

? ? ? ? ? ? 'rank': rank.get_text().strip(),

? ? ? ? ? ? 'singer': title.get_text().split('-')[0].strip(),

? ? ? ? ? ? 'song': title.get_text().split('-')[1].strip(),

? ? ? ? ? ? 'time': song_time.get_text().strip()

}

? ? ? ? print(data)

? ? ? ? # song_id = songs.insert(data) # insert db

#print(song_id)

? ? ? ? print('---------------------------------')

if __name__== '__main__':

? ? # 生成需要遍歷的url

? ? urls= ['http://www.kugou.com/yy/rank/home/{}-8888.html'.format(str(i)) for iin range(1, 24)]

? ? for urlin urls:

? ? ? ? get_info(url)

? ? ? ? time.sleep(1)


2.爬取拉勾網(wǎng)招聘信息


import json

import math

import time

import pymongo

import requests

#client = pymongo.MongoClient('localhost',27017)

#mydb = client['mydb']

#lagou = mydb['lagou']

headers= {

? ? 'Accept': 'application/json, text/javascript, */*; q=0.01',

? ? 'Accept-Encoding': 'gzip, deflate, br',

? ? 'Accept-Language': 'zh-CN,zh;q=0.8',

? ? 'Connection': 'keep-alive',

? ? 'Content-Length': '26',

? ? 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',

? ? 'Cookie': 'xxxxxxxxxxxxxxxxx',

? ? 'Host': 'www.lagou.com',

? ? 'Origin': 'https://www.lagou.com',

? ? 'Referer': 'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=',

? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',

? ? 'X-Anit-Forge-Code': '0',

? ? 'X-Anit-Forge-Token': 'None',

? ? 'X-Requested-With': 'XMLHttpRequest'

}

def get_page(url,params):

? ? html= requests.post(url,data=params,headers=headers)

? ? json_data= json.loads(html.text)

? ? total_count= json_data['content']['positionResult']['totalCount']

? ? page_number= math.ceil(total_count/15) if math.ceil(total_count/15)<30 else 30

? ? get_info(url,page_number)

def get_info(url, page):

? ? for pnin range(1,page+1):

? ? ? ? params= {

? ? ? ? ? ? 'first':'false',

? ? ? ? ? ? 'pn':str(pn),

? ? ? ? ? ? 'kd':'Python'

? ? ? ? }

? ? ? ? try:

? ? ? ? ? ? html= requests.post(url,data=params,headers=headers)

? ? ? ? ? ? json_data= json.loads(html.text)

? ? ? ? ? ? results= json_data['content']['positionResult']['result']

? ? ? ? ? ? for resultin results:

? ? ? ? ? ? ? ? infos= {

? ? ? ? ? ? ? ? ? ? 'businessZones': result['businessZones'],

? ? ? ? ? ? ? ? ? ? 'city': result['city'],

? ? ? ? ? ? ? ? ? ? 'companyFullName': result['companyFullName'],

? ? ? ? ? ? ? ? ? ? 'companyLabelList': result['companyLabelList'],

? ? ? ? ? ? ? ? ? ? 'companySize': result['companySize'],

? ? ? ? ? ? ? ? ? ? 'district': result['district'],

? ? ? ? ? ? ? ? ? ? 'education': result['education'],

? ? ? ? ? ? ? ? ? ? 'explain': result['explain'],

? ? ? ? ? ? ? ? ? ? 'financeStage': result['financeStage'],

? ? ? ? ? ? ? ? ? ? 'firstType': result['firstType'],

? ? ? ? ? ? ? ? ? ? 'formatCreateTime': result['formatCreateTime'],

? ? ? ? ? ? ? ? ? ? 'gradeDescription': result['gradeDescription'],

? ? ? ? ? ? ? ? ? ? 'imState': result['imState'],

? ? ? ? ? ? ? ? ? ? 'industryField': result['industryField'],

? ? ? ? ? ? ? ? ? ? 'jobNature': result['jobNature'],

? ? ? ? ? ? ? ? ? ? 'positionAdvantage': result['positionAdvantage'],

? ? ? ? ? ? ? ? ? ? 'salary': result['salary'],

? ? ? ? ? ? ? ? ? ? 'secondType': result['secondType'],

? ? ? ? ? ? ? ? ? ? 'workYear': result['workYear']

}

? ? ? ? ? ? ? ? print('------------------')

? ? ? ? ? ? ? ? print(infos)

? ? ? ? ? ? #? ? lagou.insert_one(infos)

? ? ? ? ? ? time.sleep(2)

? ? ? ? except requests.exceptions.ConnectionError:

? ? ? ? ? ? pass

if __name__== "__main__":

? ? url= 'https://www.lagou.com/jobs/positionAjax.json'

? ? params= {

? ? ? ? 'first':'true',

? ? ? ? 'pn':'1',

? ? ? ? 'kd':'python'

? ? }

? ? get_page(url,params)

3.爬取淘寶商品信息

4.利用scrap爬蟲抓取小豬短租網(wǎng)

scrapy startproject new

scrapy crawl new

代碼查看git項目(文章頂部)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市莹弊,隨后出現(xiàn)的幾起案子虏缸,更是在濱河造成了極大的恐慌,老刑警劉巖秕铛,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件木人,死亡現(xiàn)場離奇詭異,居然都是意外死亡钠绍,警方通過查閱死者的電腦和手機(jī)舆声,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來柳爽,“玉大人媳握,你說我怎么就攤上這事×赘” “怎么了蛾找?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長赵誓。 經(jīng)常有香客問我打毛,道長,這世上最難降的妖魔是什么俩功? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任幻枉,我火速辦了婚禮,結(jié)果婚禮上诡蜓,老公的妹妹穿的比我還像新娘熬甫。我一直安慰自己,他們只是感情好蔓罚,可當(dāng)我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布椿肩。 她就那樣靜靜地躺著,像睡著了一般脚粟。 火紅的嫁衣襯著肌膚如雪覆旱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天核无,我揣著相機(jī)與錄音扣唱,去河邊找鬼。 笑死团南,一個胖子當(dāng)著我的面吹牛噪沙,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播吐根,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼正歼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了拷橘?” 一聲冷哼從身側(cè)響起局义,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤喜爷,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后萄唇,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體檩帐,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年另萤,在試婚紗的時候發(fā)現(xiàn)自己被綠了湃密。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡四敞,死狀恐怖泛源,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情忿危,我是刑警寧澤达箍,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站铺厨,受9級特大地震影響幻梯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜努释,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一碘梢、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧伐蒂,春花似錦煞躬、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至缕减,卻和暖如春雷客,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背桥狡。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工搅裙, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人裹芝。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓部逮,卻偏偏與公主長得像,于是被迫代替她去往敵國和親嫂易。 傳聞我的和親對象是個殘疾皇子兄朋,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容