selenium爬取小女孩的故事🍉

就在刚才,lxy与小女孩的故事上了热搜,我也是看了两眼,然后直接搞吧

原贴地址:

https://www.douban.com/group/topic/32499448/?start=0

直接上代码吧:

from selenium import webdriver
import re


def down_data(html):
    data = re.findall(r'[u697cu4e3b]+.*?<p.*?>(.*?)</p>', html, re.S)
    with open('/Users/oumizushin/Desktop/text/LYR/LYRHXH.txt', 'a') as f:
        for i in data:
            f.write(i + '
')


def start_spider(web_addr, num):
    driver.get(web_addr)
    if driver.find_element_by_class_name('next'):   # 这里要注意
        down_data(driver.page_source)
        print(str(num) + "页爬取成功")
        a = driver.find_element_by_xpath('//span[@class="next"]/a')
        num += 1
        start_spider(a.get_attribute('href'), num)
    else:
        down_data(driver.page_source)
        print(num + "页爬取成功")


driver = webdriver.Chrome()
num = 1
web_addr = 'https://www.douban.com/group/topic/32499448/?start=0'
start_spider(web_addr, num)

这段代码还有一点小问题,因为豆瓣的分页的话不管首页还是尾页那个next的标签都存在,所以要换一个判断条件,可以根据页面上的总页数和当前页数的比对进行判断

 还有的话就是抓取条件的话是根据楼主的这个字段进行抓取的,所以楼主回复的评论也会被抓取下来,条件还不够完美,没多少时间,等有时间再补充完整吧~

原文地址:https://www.cnblogs.com/zhigu/p/13494484.html