85行代码实现多线程+数据文件操作+数据库存储的爬虫实例 ...

打印 上一主题 下一主题

主题 546|帖子 546|积分 1638

写在前面

这是我在接触爬虫后,写的第二个爬虫实例。
也是我在学习python后真正意义上写的第二个小项目,第一个小项目就是第一个爬虫了。
我从学习python到现在,也就三个星期不到,平时课程比较多,python是额外学习的,每天学习python的时间也就一个小时左右。
所以我目前对于python也不是特别了解,如果代码以及理解方面存在错误,欢迎大家的指正。
爬取的网站

这是一个推荐网络小说的网站。
https://www.tuishujun.com/

我之前用以下的代码实例,爬取了这个网站所有的小说数据,大概有十七万左右。
大概花了6个小时的时间,效率还是不错的,如果是在单线程的情况下,我估计在不停机24小时爬取的情况下,也需要几天。
我在刚开始写这个爬虫实例的时候,也遇到了很多问题,首先就是网上虽然有很多关于python多线程爬虫的东西,但...
除此之外,关于利用多线程操作数据库的爬虫实例也是比较少。
就解决以上问题,我找了很多资料,走了不少弯路,摸索了几天才写出了以下实例。
大家可以参考以下实例,进行拓展,写出属于自己的多线程爬虫。
需要注意的点:
在实例中我使用了ThreadPoolExecutor构造线程池的方式(大家可以找找这方面的资料看看),如果你在使用多线程的时候想要操作数据库存储数据,建议使用以上方式,要不然你会发现,在运行代码时出现各种各样的错误。
代码实例
  1. import requests
  2. import pymysql
  3. import os
  4. from lxml import etree
  5. from fake_useragent import UserAgent
  6. from concurrent.futures import ThreadPoolExecutor
  7. class tuishujunSpider(object):
  8.     def __init__(self):
  9.         if not os.path.exists('db/tuishujun'):
  10.             os.makedirs('db/tuishujun')
  11.         else:
  12.             pass
  13.         self.f = open('./db/tuishujun/tuishujun.txt', 'a', encoding='utf-8')
  14.         self.con = pymysql.connect(host='localhost', user='root', password='123456789', database='novel',
  15.                                    charset='utf8', port=3306)
  16.         self.cursor = self.con.cursor()
  17.         self.cursor.execute(" SHOW TABLES LIKE 'tuishujun' ")
  18.         judge = self.cursor.fetchone()
  19.         if judge:
  20.             pass
  21.         else:
  22.             self.cursor.execute("""create table tuishujun
  23.                             ( id BIGINT NOT NULL AUTO_INCREMENT,
  24.                               cover VARCHAR(255),
  25.                               name VARCHAR(255),
  26.                               author VARCHAR(255),
  27.                               source VARCHAR(255),
  28.                               intro LONGTEXT,
  29.                               PRIMARY KEY (id))
  30.                            """)
  31.         self.con.commit()
  32.         self.cursor.close()
  33.         self.con.close()
  34.     def start(self, page):
  35.         con = pymysql.connect(
  36.             host='localhost', user='root', password='123456789', database='novel', charset='utf8', port=3306)
  37.         cursor = con.cursor()
  38.         headers = {
  39.             'User-Agent': UserAgent().random
  40.         }
  41.         url = 'https://www.tuishujun.com/books/' + str(page)
  42.         r = requests.get(url, headers=headers)
  43.         if r.status_code == 500:
  44.             return
  45.         else:
  46.             html = etree.HTML(r.text)
  47.             book = {}
  48.             book['id'] = str(page)
  49.             try:
  50.                 cover = html.xpath('//*[@id="__layout"]/div/div[2]/div/div[1]/div/div[1]/div[1]/div[1]/img/@src')[0]
  51.             except IndexError:
  52.                 cover = ''
  53.             book['cover'] = cover
  54.             name = \
  55.                 html.xpath(
  56.                     '//*[@id="__layout"]/div/div[2]/div/div[1]/div/div[1]/div[1]/div[2]/div/div[1]/h3/text()')[0]
  57.             book['name'] = name
  58.             author = \
  59.                 html.xpath(
  60.                     '//*[@id="__layout"]/div/div[2]/div/div[1]/div/div[1]/div[1]/div[2]/div/div[2]/a/text()')[
  61.                     0].strip()
  62.             author = author.replace("\n", "")
  63.             book['author'] = author
  64.             source = \
  65.                 html.xpath('//*[@id="__layout"]/div/div[2]/div/div[1]/div/div[1]/div[1]/div[2]/div/div[5]/text()')[
  66.                     0]
  67.             book['source'] = source
  68.             intro = html.xpath('//*[@id="__layout"]/div/div[2]/div/div[1]/div/div[1]/div[2]/text()')[0]
  69.             intro = intro.replace(" ", "")
  70.             intro = intro.replace("\n", "")
  71.             book['intro'] = intro
  72.             self.f.write(str(book) + '\n')
  73.             cursor.execute("insert into tuishujun(id,cover,name,author,source,intro) "
  74.                            "values(%s,%s,%s,%s,%s,%s)",
  75.                            (book['id'], book['cover'], book['name'], book['author'],
  76.                             book['source'], book['intro']))
  77.             con.commit()
  78.             cursor.close()
  79.             con.close()
  80.             print(book)
  81.     def run(self):
  82.         pages = range(1, 200000)
  83.         with ThreadPoolExecutor() as pool:
  84.             pool.map(self.start, pages)
  85. if __name__ == '__main__':
  86.     spider = tuishujunSpider()
  87.     spider.run()
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

怀念夏天

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表