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

 3506

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


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

  1. import re
  2. import bs4
  3. import urllib.request
  4.   
  5. url_home = 'https://www.zztuku.com/'  #要采集的网站
  6. url_pattern = url_home + '([\s\S]*)\.html' #正则表达式匹配文章页面,此处需完善为更好的写法
  7. url_set = set()
  8. url_cache = set()
  9. url_count = 0
  10. url_maxCount = 1000  #最大采集数量
  11.   
  12. #采集匹配文章内容的href标签
  13. def spiderURL(url, pattern):
  14.    html = urllib.request.urlopen(url).read().decode('utf8')
  15.    soup = bs4.BeautifulSoup(html, 'html.parser')
  16.    links = soup.find_all('a', href = re.compile(pattern))
  17.    for link in links:
  18.        if link['href'] not in url_cache:
  19.            url_set.add(link['href'])
  20.    return soup
  21.   
  22. #采集的过程  异常处理还需要完善,对于一些加了防采集的站,还需要处理header的,下次我们再学习
  23. spiderURL(url_home, url_pattern)
  24.   
  25. while len(url_set) != 0:
  26.    try:
  27.        url = url_set.pop()
  28.        url_cache.add(url)
  29.        soup = spiderURL(url, url_pattern)
  30.        page = soup.find('div', {'class':'content'})
  31.   
  32.        title = page.find('h1').get_text()
  33.        autor = page.find('h4').get_text()
  34.        content = page.find('article').get_text()
  35.   
  36.        print(title, autor, url)
  37.    except Exception as e:
  38.        print(url, e)
  39.        continue
  40.    else:
  41.        url_count += 1
  42.    finally:
  43.        if url_count == url_maxCount:
  44.            break
  45.   
  46. print('一共采集了: ' + str(url_count) + ' 条数据')


本文网址:https://www.zztuku.com/detail-13814.html
站长图库 - Python批量采集WordPress网站数据爬虫脚本
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐