python爬虫及案例详解(附代码)

安装三大库
1、requests
2、BeautifulSoup
3、lxml
有的网站做了相应的反爬虫,不能用普通方法爬取网站数据。
这里我用python爬取了几个网站的数据,分别存入csv文件,mysql数据库,并用简单工具对数据进行了分析和可视化。具体代码和详解请参考
代码下载
有帮助到您,记得给颗🌟🌟

一、爬取糗事百科数据(pachong.py)

1、用python爬取糗事百科的用户地址,并且解析出地址的经纬度,在地图上通过热力图绘制出来
2、把数据保存到excel表中,再用BDP绘制出热力图

2C377268-40D3-440F-9B6F-8766F5E20577.png

二、多进程快速爬取豆瓣电影250数据数据(multipelPrcessCrawer.py)

1、导入Pool进程池,开四个进程爬取豆瓣电影排行信息

2、存入mysql数据库中

三、lxml爬取小说数据(lxml-scrawer.py)

四、爬取《斗破苍穹》小说原文(doupo.py)

1、爬取《斗破苍穹》小说所有章节的内容

五、jieba统计词频(jiebatest.py)

1、导入jieba包,统计《斗破苍穹》词频

2、用wordart可视化


image.png

B763170B-93E1-4F1C-A248-77EEBFAA1BB2.png

https://www.cnblogs.com/sss4/p/7809821.html


import requests
from bs4 import BeautifulSoup
res = requests.get("http://xa.xiaozhu.com/")
soup = BeautifulSoup(res.text,'html.parser')
prices = soup.select('#page_list > ul > li:nth-of-type(7) > div.result_btm_con.lodgeunitname > span.result_price > i')
for price in prices:
    print(price)

输出本页所有的价格
page_list > ul > li > div.result_btm_con.lodgeunitname > span.result_price > i

酷狗排行榜top500数据爬取

import requests
from bs4 import BeautifulSoup
res = requests.get("http://xa.xiaozhu.com/")
soup = BeautifulSoup(res.text,'html.parser')
prices = soup.select('#page_list > ul > li > div.result_btm_con.lodgeunitname > span.result_price > i')
for price in prices:
print(price.get_text())

import requests
from bs4 import BeautifulSoup
import time

def get_info(url):
    wb_data = requests.get(url)
    soup = BeautifulSoup(wb_data.text, 'lxml')
    ranks = soup.select('span.pc_temp_num')
    titles = soup.select('div.pc_temp_songlist > ul > li > a')
    times = soup.select('span.pc_temp_tips_r > span')
    for rank,title,time in zip(ranks,titles,times):
        data = {
            'rank':rank.get_text().strip(),
            'singer':title.get_text().split('-')[0],
            'song':title.get_text().split('-')[1],
            'time':time.get_text().strip()
        }
        print(data)
if __name__ =='__main__':
    urls = ['http://www.kugou.com/yy/rank/home/{}-8888.html'.format(str(i)) for i in range(1,24)]
    for url in urls:
        get_info(url)
    time.sleep(1)

爬取小说内容保存到txt文件

import requests
import re
import time
f = open('/Users/jalynnxi/Desktop/doupo.txt','a+')
def get_info(url):
    res = requests.get(url)
    if res.status_code == 200:
        contents = re.findall('<p>(.*?)</p>',res.content.decode('utf-8'),re.S)
        for content in contents:
            f.write(content+'\n')
        else:
            pass
if __name__ =='__main__':
    urls = ['http://m.doupoxs.com/doupocangqiong/{}.html'.format(str(i)) for i in range(1,1624)]
    for url in urls:
        get_info(url)
        time.sleep(1)
f.close()

爬取糗事百科的用户信息

import requests
import re
import time
info_lists = []
def judgment_sex(class_name):
    if class_name == 'womenIcon':
        return '女'
    else:
        return '男'
def get_info(url):
    res = requests.get(url)
    ids = re.findall('<h2>(.*?)</h2>',res.text,re.S)
    levels = re.findall('<div class="articleGender \D+Icon">(.*?)</div>',res.text,re.S)
    sexs = re.findall('<div class="articleGender (.*?)"', res.text,re.S)
    contents = re.findall('<div class="content">.*?<span>(.*?)</span>', res.text,re.S)
    laughs = re.findall('<span class="stats-vote"><i class="number">(\d+)</i>',res.text,re.S)
    comments = re.findall('<i class="number">(\d+)</i> 评论',res.text,re.S)
    for id, level, sex, content,laugh,comment in zip(ids, levels, sexs, contents, laughs, comments):
        info = {
            'id': id,
            'level': level,
            'sex': judgment_sex(sex),
            'content': content,
            'laugh': laugh,
            'comment': comment
        }
    info_lists.append(info)
    print (info)
if __name__ == '__main__':
    urls = ['https://www.qiushibaike.com/8hr/page/{}/'.format(str(i)) for i in range(1,10)]
    for url in urls:
        get_info(url)

    for info_list in info_lists:
        f = open('/Users/jalynnxi/Desktop/qiushi.txt', 'a+')
        try:
            f.write(info_list['id']+'\n')
            f.write(info_list['level'] + '\n')
            f.write(info_list['sex'] + '\n')
            f.write(info_list['content'] + '\n')
            f.write(info_list['laugh'] + '\n')
            f.write(info_list['comment'] + '\n')
            f.close()
        except UnicodeEncodeError:
            pass

把数据写如excel

import xlwt
book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('Sheet1')
sheet.write(0,0,'python')
book.save('test.xls')

爬取书名、作者、分类等信息存入excel

import xlwt
import requests
from lxml import etree
import time

all_info_list = []


def get_info(url):
    html = requests.get(url)
    selector = etree.HTML(html.text)
    infos = selector.xpath('//ul[@class="all-img-list cf"]/li')
    # infos = selector.xpath('/html/body/div[2]/div[5]/div[2]/div[2]/div/ul/li[1]')
    # print (infos)
    # '/html/body/div[2]/div[5]/div[2]/div[2]/div/ul/li[1]'
    for info in infos:
        title = info.xpath('div[2]/h4/a/text()')[0]
        author = info.xpath('div[2]/p[1]/a[1]/text()')[0]
        style_1 = info.xpath('div[2]/p[1]/a[2]/text()')[0]
        style_2 = info.xpath('div[2]/p[1]/a[3]/text()')[0]
        style = style_1 + '.' + style_2
        complete = info.xpath('div[2]/p[1]/span/text()')[0]
        introduce = info.xpath('div[2]/p[2]/text()')[0]
        word = info.xpath('div[2]/p[3]/span/text()')[0]
        info_list = [title, author, style, complete, introduce, word]
        all_info_list.append(info_list)


if __name__ == '__main__':
    urls = ['https://www.qidian.com/all?page={}'.format(str(i)) for i in range(1,3)]
    for url in urls:
        get_info(url)
    header = ['title', 'author', 'style', 'complete', 'introduce', 'word']
    book = xlwt.Workbook(encoding='utf-8')
    sheet = book.add_sheet('Sheet1')
    for h in range(len(header)):
        sheet.write(0, h, header[h])
    i = 1
    for list1 in all_info_list:
        j = 0
        for data in list1:
            sheet.write(i, j, data)
            j += 1
        i += 1
book.save('xiaoshuo.xls')

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容