Python批量采集wordpress网站数据爬虫脚本

ゞ 浴缸里的玫瑰 2024-03-16 10:17 175阅读 0赞

分享一段非常简单的Python批量采集wordpress网站数据的爬虫脚本,实现采集wordpress程序的网站的整站数据的爬虫程序。从首页开始,抓取href标签,到子页面后还是要继续找href标签,采用Python递归方法,直接贴代码吧!








1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

import re

import bs4

import urllib.request

  

url_home = ‘https://www.che0.com/‘  #要采集的网站

url_pattern = url_home + ‘([\s\S]*).html’ #正则表达式匹配文章页面,此处需完善为更好的写法

url_set = set()

url_cache = set()

url_count = 0

url_maxCount = 1000  #最大采集数量

  

#采集匹配文章内容的href标签

def spiderURL(url, pattern):

   html = urllib.request.urlopen(url).read().decode(‘utf8’)

   soup = bs4.BeautifulSoup(html, ‘html.parser’)

   links = soup.find_all(‘a’, href = re.compile(pattern))

   for link in links:

       if link[‘href’not in url_cache:

           url_set.add(link[‘href’])

   return soup

  

#采集的过程  异常处理还需要完善,对于一些加了防采集的站,还需要处理header的,下次我们再学习

spiderURL(url_home, url_pattern)

  

while len(url_set) != 0:

   try:

       url = url_set.pop()

       url_cache.add(url)

       soup = spiderURL(url, url_pattern)

       page = soup.find(‘div’, { ‘class’:‘content’})

  

       title = page.find(‘h1’).get_text()

       autor = page.find(‘h4’).get_text()

       content = page.find(‘article’).get_text()

  

       print(title, autor, url)

   except Exception as e:

       print(url, e)

       continue

   else:

       url_count += 1

   finally:

       if url_count == url_maxCount:

           break

  

print(‘一共采集了: ’ + str(url_count) + ‘ 条数据’)

发表评论

表情:
评论列表 (有 0 条评论,175人围观)

还没有评论,来说两句吧...

相关阅读

    相关 批量数据脚本

    > 本教程中所使用的数据库的建表语句都在“MySQL高阶教程索引”这篇文章中,点击链接直达:[索引&建表语句][Link 1] > 摘要:本文主要介绍查询截取分析模块的批量数