7个非常经典的 Python爬虫 案例(附源码)

DevOps技术栈

共 31405字,需浏览 63分钟

 · 2023-09-07

原文链接:https://blog.csdn.net/m0_64336780/article/details/127454511

本次的7个python爬虫小案例涉及到了re正则、xpath、beautiful soup、selenium等知识点,非常适合刚入门python爬虫的小伙伴参考学习。注:若涉及到版权或隐私问题,请及时联系我删除即可。

 本次选取的是某吧中的NBA吧中的一篇帖子,帖子标题是“克莱和哈登,谁历史地位更高”。爬取的目标是帖子里面的回复内容。

源程序和关键结果截图:


           
           
    url = f'https://tieba.baidu.com/p/7882177660?pn={page}'
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'

    resp = requests.get(url,headers=headers)
    comments = re.findall('style="display:;"> (.*?)</div>',html)

    users = re.findall('class="p_author_name j_user_card" href=".*?" target="_blank">(.*?)</a>',html)

    comment_times = re.findall('楼</span><span class="tail-info">(.*?)</span><div',html)for u,c,t in zip(users,comments,comment_times):

    if 'img' in c or 'div' in c or len(u)>50:csvwriter.writerow((u,t,c))
    if __name__ == '__main__':with open('01.csv','a',encoding='utf-8')as f:csvwriter = csv.writer(f)csvwriter.writerow(('评论用户','评论时间','评论内容'))

 本次选取的小说网址是某小说网,这里我们选取第一篇小说进行爬取

然后通过分析网页源代码分析每章小说的链接

找到链接的位置后,我们使用Xpath来进行链接和每一章标题的提取

在这里,因为涉及到多次使用requests发送请求,所以这里我们把它封装成一个函数,便于后面的使用

每一章的链接获取后,我们开始进入小说章节内容页面进行分析

通过网页分析,小说内容都在网页源代码中,属于静态数据

这里我们选用re正则表达式进行数据提取,并对最后的结果进行清洗

然后我们需要将数据保存到数据库中,这里我将爬取的数据存储到mysql数据库中,先封住一下数据库的操作

接着将爬取到是数据进行保存

最后一步就是使用多线程来提高爬虫效率,这里我们创建了5个线程的线程池

 源代码及结果截图:


           
           
    from concurrent.futures import ThreadPoolExecutor
    conn = pymysql.connect(host="127.0.0.1",
    def close_conn(conn, cursor):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'}resp = requests.get(url, headers=headers)tree = etree.HTML(resp.text)tree,_ = get_xpath_resp(url)novel_name = tree.xpath('//*[@id="info"]/h1/text()')[0]dds = tree.xpath('/html/body/div[4]/dl/dd')

    title = d.xpath('./a/text()')[0]

    link = d.xpath('./a/@href')[0]

    link_list.append(chapter_url)return title_list,link_list,novel_name
    def get_content(novel_name,title,url):
    conn, cursor = get_conn()sql = 'INSERT INTO novel(novel_name,chapter_name,content) VALUES(%s,%s,%s)'tree,resp = get_xpath_resp(url)content = re.findall('<div id="content">(.*?)</div>',resp.text)[0]content = content.replace('<br />','\n').replace('&nbsp;',' ').replace('全本小说网 www.qb5.tw,最快更新<a href="https://www.qb5.tw/book_116659/">宇宙职业选手</a>最新章节!<br><br>','')cursor.execute(sql,[novel_name,title,content])
    if __name__ == '__main__':

    title_list, link_list, novel_name = get_chapters('https://www.qb5.tw/book_116659/')with ThreadPoolExecutor(5) as t:for title,link in zip(title_list,link_list):t.submit(get_content, novel_name,title,link)

 3. 分别使用XPath和Beautiful Soup4两种方式爬取并保存非异步加载的“某瓣某排行榜”如https://movie.douban.com/top250的名称、描述、评分和评价人数等数据。

 先分析:

首先,来到某瓣Top250页面,首先使用Xpath版本的来抓取数据,先分析下电影列表页的数据结构,发下都在网页源代码中,属于静态数据

接着我们找到数据的规律,使用xpath提取每一个电影的链接及电影名

然后根据链接进入到其详情页

分析详情页的数据,发现也是静态数据,继续使用xpath提取数据

最后我们将爬取的数据进行存储,这里用csv文件进行存储

接着是Beautiful Soup4版的,在这里,我们直接在电影列表页使用bs4中的etree进行数据提取

最后,同样使用csv文件进行数据存储

源代码即结果截图:

XPath版:


           
           
url = f'https://movie.douban.com/top250?start={page*25}&filter='headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.35 Safari/537.36',}resp = requests.get(url,headers=headers)tree = etree.HTML(resp.text)

href_list = tree.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[1]/a/@href')

name_list = tree.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[2]/div[1]/a/span[1]/text()')for url,name in zip(href_list,name_list):sleep(1 + random.random())
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.35 Safari/537.36','Host': 'movie.douban.com',

resp = requests.get(url,headers=headers)
dir = tree.xpath('//*[@id="info"]/span[1]/span[2]/a/text()')[0]

type_ = re.findall(r'property="v:genre">(.*?)</span>',html)
country = re.findall(r'地区:</span> (.*?)<br',html)[0]

time = tree.xpath('//*[@id="content"]/h1/span[2]/text()')[0]



rate = tree.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/strong/text()')[0]

people = tree.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/div/div[2]/a/span/text()')[0]print(name,dir,type_,country,time,rate,people)csvwriter.writerow((name,dir,type_,country,time,rate,people))

if __name__ == '__main__':

with open('03-movie-xpath.csv','a',encoding='utf-8',newline='')as f:csvwriter = csv.writer(f)

csvwriter.writerow(('电影名称','导演','电影类型','国家','上映年份','评分','评论人数'))

sleep(3 + random.random())

Beautiful Soup4版: 


           
           
    from bs4 import BeautifulSoup

    page = urllib.request.Request(url, headers=headers)page = urllib.request.urlopen(page)



    soup = BeautifulSoup(contents, "html.parser")


    for tag in soup.find_all(attrs={"class": "item"}):

    num = tag.find('em').get_text()

    infofile.write(num + "\r\n")

    name = tag.find_all(attrs={"class": "title"})zwname = name[0].get_text()

    infofile.write("[中文名称]" + zwname + "\r\n")

    url_movie = tag.find(attrs={"class": "hd"}).aurls = url_movie.attrs['href']

    infofile.write("[网页链接]" + urls + "\r\n")

    info = tag.find(attrs={"class": "star"}).get_text()info = info.replace('\n', ' ')
    info = tag.find(attrs={"class": "inq"})

    content = info.get_text()

    infofile.write(u"[影评]" + content + "\r\n")

    if __name__ == '__main__':

    infofile = codecs.open("03-movie-bs4.txt", 'a', 'utf-8')

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}

    url = 'https://movie.douban.com/top250?start=' + str(num) + '&filter='

    sleep(5 + random.random())infofile.write("\r\n\r\n")

 4.实现某东商城某商品评论数据的爬取(评论数据不少于100条,包括评论内容、时间和评分)。

 先分析:

 本次选取的某东官网的一款联想笔记本电脑,数据为动态加载的,通过开发者工具抓包分析即可。

源代码及结果截图:


           
           

    url = 'https://club.jd.com/comment/productPageComments.action'

    'productId': 100011483893,


    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.35 Safari/537.36','referer': 'https://item.jd.com/'

    resp = requests.get(url,params=params,headers=headers).json()comments = resp['comments']

    content = comment['content']content = content.replace('\n','')comment_time = comment['creationTime']

    print(score,comment_time,content)csvwriter.writerow((score,comment_time,content))



    if __name__ == '__main__':with open('04.csv','a',encoding='utf-8',newline='')as f:csvwriter = csv.writer(f)csvwriter.writerow(('评分','评论时间','评论内容'))

5. 实现多种方法模拟登录某乎,并爬取与一个与江汉大学有关问题和答案。

首先使用selenium打开某乎登录页面,接着使用手机进行二维码扫描登录

进入页面后,打开开发者工具,找到元素,,定位输入框,输入汉江大学,然后点击搜索按钮

 

以第二条帖子为例,进行元素分析 。

源代码及结果截图:


           
           
    from selenium.webdriver.chrome.service import Servicefrom selenium.webdriver import Chrome,ChromeOptionsfrom selenium.webdriver.common.by import By

    warnings.filterwarnings("ignore")

    service = Service('chromedriver.exe')options = ChromeOptions()

    options.add_experimental_option('excludeSwitches', ['enable-automation','enable-logging'])options.add_experimental_option('useAutomationExtension', False)

    driver = Chrome(service=service,options=options)

    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {

    Object.defineProperty(navigator, 'webdriver', {
    driver.get('https://www.zhihu.com/')
    driver.find_element(By.ID,'Popover1-toggle').click()

    driver.find_element(By.ID,'Popover1-toggle').send_keys('汉江大学')

    driver.find_element(By.XPATH,'//*[@id="root"]/div/div[2]/header/div[2]/div[1]/div/form/div/div/label/button').click()

    driver.implicitly_wait(20)

    title = driver.find_element(By.XPATH,'//*[@id="SearchMain"]/div/div/div/div/div[2]/div/div/div/h2/div/a/span').text

    driver.find_element(By.XPATH,'//*[@id="SearchMain"]/div/div/div/div/div[2]/div/div/div/div/span/div/button').click()
    content = driver.find_element(By.XPATH,'//*[@id="SearchMain"]/div/div/div/div/div[2]/div/div/div/div/span[1]/div/span/p').text

    driver.find_element(By.XPATH,'//*[@id="SearchMain"]/div/div/div/div/div[2]/div/div/div/div/div[3]/div/div/button[1]').click()

    driver.find_element(By.XPATH,'//*[@id="SearchMain"]/div/div/div/div/div[2]/div/div/div/div[2]/div/div/div[2]/div[2]/div/div[3]/button').click()
    divs = driver.find_elements(By.XPATH,'/html/body/div[6]/div/div/div[2]/div/div/div/div[2]/div[3]/div')
    comment = div.find_element(By.XPATH,'./div/div/div[2]').text
    if __name__ == '__main__':

    with open('05.txt','a',encoding='utf-8')as f:

 6. 综合利用所学知识,爬取某个某博用户前5页的微博内容。

这里我们选取了人民日报的微博内容进行爬取,具体页面我就不放这了,怕违规。

源代码及结果截图:


           
           
    url = f'https://weibo.com/ajax/statuses/mymblog?uid=2803301701&page={page}&feature=0&since_id=4824543023860882kp{page}'
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36','cookie':'SINAGLOBAL=6330339198688.262.1661412257300; ULV=1661412257303:1:1:1:6330339198688.262.1661412257300:; PC_TOKEN=8b935a3a6e; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WWoQDW1G.Vsux_WIbm9NsCq5JpX5KMhUgL.FoMNShMN1K5ESKq2dJLoIpjLxKnL1h.LB.-LxKqLBoBLB.-LxKqLBKeLB--t; ALF=1697345086; SSOLoginState=1665809086; SCF=Auy-TaGDNaCT06C4RU3M3kQ0-QgmTXuo9D79pM7HVAjce1K3W92R1-fHAP3gXR6orrHK_FSwDsodoGTj7nX_1Hw.; SUB=_2A25OTkruDeRhGeFJ71UW-S7OzjqIHXVtOjsmrDV8PUNbmtANLVKmkW9Nf9yGtaKedmyOsDKGh84ivtfHMGwvRNtZ; XSRF-TOKEN=LK4bhZJ7sEohF6dtSwhZnTS4; WBPSESS=PfYjpkhjwcpEXrS7xtxJwmpyQoHWuGAMhQkKHvr_seQNjwPPx0HJgSgqWTZiNRgDxypgeqzSMsbVyaDvo7ng6uTdC9Brt07zYoh6wXXhQjMtzAXot-tZzLRlW_69Am82CXWOFfcvM4AzsWlAI-6ZNA=='

    resp = requests.get(url,headers=headers)data_list = resp.json()['data']['list']

    created_time = item['created_at']author = item['user']['screen_name']

    reposts_count = item['reposts_count']comments_count = item['comments_count']attitudes_count = item['attitudes_count']csvwriter.writerow((created_time,author,title,reposts_count,comments_count,attitudes_count))print(created_time,author,title,reposts_count,comments_count,attitudes_count)



    if __name__ == '__main__':

    with open('06-2.csv','a',encoding='utf-8',newline='')as f:csvwriter = csv.writer(f)

    csvwriter.writerow(('发布时间','发布作者','帖子标题','转发数','评论数','点赞数'))

 7.自选一个热点或者你感兴趣的主题,爬取数据并进行简要数据分析(例如,通过爬取电影的名称、类型、总票房等数据统计分析不同类型电影的平均票房,十年间每年票房冠军的票房走势等;通过爬取中国各省份地区人口数量,统计分析我国人口分布等)。

本次选取的网址是艺恩娱数,目标是爬取里面的票房榜数据,通过开发者工具抓包分析找到数据接口,然后开始编写代码进行数据抓取。 

源代码及结果截图:


           
           
    import matplotlib.pyplot as plt
    warnings.filterwarnings('ignore')plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = False
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',}

    'r''0.9936776079863086',
    resp = requests.post('https://ys.endata.cn/enlib-api/api/home/getrank_mainland.do', headers=headers, data=data)data_list = resp.json()['data']['table0']
    MovieName = item['MovieName']ReleaseTime = item['ReleaseTime']TotalPrice = item['BoxOffice']AvgPrice = item['AvgBoxOffice']AvgAudienceCount = item['AvgAudienceCount']

    csvwriter.writerow((rank,MovieName,ReleaseTime,TotalPrice,AvgPrice,AvgAudienceCount))print(rank,MovieName,ReleaseTime,TotalPrice,AvgPrice,AvgAudienceCount)
    data = pd.read_csv('07.csv')

    data['年份'] = data['上映时间'].apply(lambda x: x.split('-')[0])

    df1 = data.groupby('年份')['总票房(万)'].sum()plt.figure(figsize=(6, 6))plt.pie(df1, labels=df1.index.to_list(), autopct='%1.2f%%')plt.title('各年度上榜电影总票房占比')



    df1 = data.groupby('年份')['总票房(万)'].sum()plt.figure(figsize=(6, 6))plt.plot(df1.index.to_list(), df1.values.tolist())plt.title('各年度上榜电影总票房趋势')
    print(data.sort_values(by='平均票价', ascending=False)[['年份', '电影名称', '平均票价']].head(10))

    print(data.sort_values(by='平均场次', ascending=False)[['年份', '电影名称', '平均场次']].head(10))
    if __name__ == '__main__':

    with open('07.csv', 'w', encoding='utf-8',newline='') as f:csvwriter = csv.writer(f)

    csvwriter.writerow(('排名', '电影名称', '上映时间', '总票房(万)', '平均票价', '平均场次'))

 

 从年度上榜电影票房占比来看,2019年占比最高,说明2019年这一年的电影质量都很不错,上榜电影多而且票房高。

从趋势来看,从2016年到2019年,上榜电影总票房一直在增长,到2019年达到顶峰,说明这一年电影是非常的火爆,但是从2020年急剧下滑,最大的原因应该是这一年年初开始爆发疫情,导致贺岁档未初期上映,而且由于疫情影响,电影院一直处于关闭状态,所以这一年票房惨淡。


              
              
往期推荐

 

                    
                    
                     
                     
                        
                        
          
          
              
              
                
                

                  
                  

点亮,服务器三年不宕机

浏览 937
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报