赞
踩
本次的7个python爬虫小案例涉及到了re正则、xpath、beautiful soup、selenium等知识点,非常适合刚入门python爬虫的小伙伴参考学习。<注:若涉及到版权或隐私问题,请及时联系我删除即可。>
前排提示:文末有CSDN官方认证Python入门资料包!
本次选取的是某吧中的NBA吧中的一篇帖子,帖子标题是“克莱和哈登,谁历史地位更高”。爬取的目标是帖子里面的回复内容。
源程序和关键结果截图:
import csv import requests import re import time def main(page): url = f'https://tieba.baidu.com/p/7882177660?pn={page}' 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) html = resp.text # 评论内容 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: continue csvwriter.writerow((u,t,c)) print(u,t,c) print(f'第{page}页爬取完毕') if __name__ == '__main__': with open('01.csv','a',encoding='utf-8')as f: csvwriter = csv.writer(f) csvwriter.writerow(('评论用户','评论时间','评论内容')) for page in range(1,8): # 爬取前7页的内容 main(page) time.sleep(2)
本次选取的小说网址是某小说网,这里我们选取第一篇小说进行爬取
然后通过分析网页源代码分析每章小说的链接
找到链接的位置后,我们使用Xpath来进行链接和每一章标题的提取
在这里,因为涉及到多次使用requests发送请求,所以这里我们把它封装成一个函数,便于后面的使用
每一章的链接获取后,我们开始进入小说章节内容页面进行分析
通过网页分析,小说内容都在网页源代码中,属于静态数据
这里我们选用re正则表达式进行数据提取,并对最后的结果进行清洗
然后我们需要将数据保存到数据库中,这里我将爬取的数据存储到mysql数据库中,先封住一下数据库的操作
接着将爬取到是数据进行保存
最后一步就是使用多线程来提高爬虫效率,这里我们创建了5个线程的线程池
源代码及结果截图:
import requests from lxml import etree import re import pymysql from time import sleep from concurrent.futures import ThreadPoolExecutor def get_conn(): # 创建连接 conn = pymysql.connect(host="127.0.0.1", user="root", password="root", db="novels", charset="utf8") # 创建游标 cursor = conn.cursor() return conn, cursor def close_conn(conn, cursor): cursor.close() conn.close() def get_xpath_resp(url): 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) # 用etree解析html return tree,resp def get_chapters(url): tree,_ = get_xpath_resp(url) # 获取小说名字 novel_name = tree.xpath('//*[@id="info"]/h1/text()')[0] # 获取小说数据节点 dds = tree.xpath('/html/body/div[4]/dl/dd') title_list = [] link_list = [] for d in dds[:15]: title = d.xpath('./a/text()')[0] # 章节标题 title_list.append(title) link = d.xpath('./a/@href')[0] # 章节链接 chapter_url = url +link # 构造完整链接 link_list.append(chapter_url) return title_list,link_list,novel_name def get_content(novel_name,title,url): try: cursor = None conn = None conn, cursor = get_co
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。