scrapy+selenium爬取UC头条网站

简介: Scrapy是Python优秀的爬虫框架,selenium是非常好用的自动化WEB测试工具,两者结合可以非常容易对动态网页进行爬虫。本文的需求是抓取UC头条各个板块的内容。

Scrapy是Python优秀的爬虫框架,selenium是非常好用的自动化WEB测试工具,两者结合可以非常容易对动态网页进行爬虫。
本文的需求是抓取UC头条各个板块的内容。UC头条(https://news.uc.cn/ )网站没有提供搜索入口,只能每个板块的首页向下滚动鼠标加载更多。要对这样的网站进行检索,抓取其内容,采用一般的scrapy请求方式,每次只能获取最新的10条数据,分析其JS请求,发现参数过于复杂,没有规律。如果想获取更多数据,则需要采用模拟浏览器的方法,这时候selenium就派上用场了。

image

1,定义spider

模拟从百度搜索进入,这个步骤可以省略,主要为了跳到parse函数

class UCTouTiaoSpider(VideoBaseSpider):
    name = "uctoutiao_spider"
    df_keys = ['人物', '百科', '乌镇']
 
 
    def __init__(self, scrapy_task_id=None, *args, **kwargs):        
        self.url_src = "http://www.baidu.com"
 
    def start_requests(self):
 
        requests = []
        request = scrapy.Request("http://www.baidu.com", callback=self.parse)
        requests.append(request)       
        return requests

2,parse函数

def parse(self, response):
    self.log(response.url)
 
 
    urls = ["https://news.uc.cn/",
            "https://news.uc.cn/c_redian/",
            # "https://news.uc.cn/c_shipin/",
            # "https://news.uc.cn/c_gaoxiao/",
            "https://news.uc.cn/c_shehui/",
            "https://news.uc.cn/c_yule/",
            "https://news.uc.cn/c_keji/",
            "https://news.uc.cn/c_tiyu/",
            "https://news.uc.cn/c_qiche/",
            "https://news.uc.cn/c_caijing/",
            "https://news.uc.cn/c_junshi/",
            "https://news.uc.cn/c_tansuo/",
            "https://news.uc.cn/c_lishi/",
            "https://news.uc.cn/c_youxi/",
            "https://news.uc.cn/c_lvyou/",
            "https://news.uc.cn/news/",
            "https://news.uc.cn/c_shishang/",
            "https://news.uc.cn/c_jiankang/",
            "https://news.uc.cn/c_guoji/",
            "https://news.uc.cn/c_yuer/",
            "https://news.uc.cn/c_meishi/"]
      
    # 启动浏览器,这里用的火狐,如果在linux环境下可以用PhantomJS,稳定性稍微差点,有内存泄露的风险。
    driver = webdriver.Firefox()
    for url in urls:
        try:
            print(url)
            driver.get(url)
            #模拟鼠标滚到底部(加载100条数据)
            for _ in range(10):
                driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
                driver.implicitly_wait(10)  # 隐性等待,最长10秒
 
            # print driver.page_source
            soup = bs(driver.page_source, 'lxml')
            articles = soup.find_all(href=re.compile("/a_\w+?/"), text=re.compile(".+"))
            for article in articles:
                for key in self.df_keys:
                    item = VideoItem()  #自定义的Item
                    item['title'] = article.text
                    item['href'] = article['href']                    
                    self.log(item)
                    yield item
 
        except Exception as e:
            print e
            if driver == None:
                driver = webdriver.Firefox()
 
    if driver != None:
        driver.quit()

真正的实现部分比较简单,几句代码就搞定了。

附:

selenium使用实例

1,切换焦点至新窗口

在页面上点击一个button, 然后打开了一个新的window, 将当前IWebDriver的focus切换到新window,使用IWebDriver.SwitchTo().Window(string windowName)。

例如, 我点击按钮以后弹出一个名字叫做"Content Display"的window, 要切换焦点到新窗口的方法是, 首先,获得新window的window name, 大家不要误以为page tile就是window name 哦, 如果你使用driver.SwitchTo().Window("Content Display")是找不到window name 叫做"Content Display"的窗口的, 其实Window Name 是一长串数字,类似“59790103-4e06-4433-97a9-b6e519a84fd0”。

要正确切换到"Content Display"的方法是:

  1. 获得当前所有的WindowHandles。

  2. 循环遍历到所有的window, 查找window.title与"Content Display"相符的window返回。

for handle in dr.window_handles:
    dr.switch_to.window(handle)
    print dr.title
    if len(dr.title) == '目标窗口标题':
        break

参考:Selenium - IWebDriver.SwitchTo() frame 和 Window 的用法

2 ,移至底部

driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")

3,移动至指定元素

某些按钮点击时必须可见,于是要把屏幕移动到按钮可见的区域

element = driver.find_element_by_xpath("//a[@class='p-next']")
element.location_once_scrolled_into_view
 
#或者
driver.set_window_size(800,800)
element = driver.find_element_by_xpath("//a[@class='p-next']")
js = "window.scrollTo({},{});".format(element.location['x'], element.location['y'] - 100)
driver.execute_script(js)

参考:
Python selenium —— 一定要会用selenium的等待,三种等待方式解读

链接博客:http://kekefund.com/2017/12/06/scrapy-and-selenium/

目录
相关文章
|
3月前
|
Web App开发 前端开发 IDE
Airtest-Selenium实操小课①:爬取新榜数据
Airtest-Selenium实操小课①:爬取新榜数据
|
3月前
|
数据采集 中间件 Python
Scrapy爬虫:利用代理服务器爬取热门网站数据
Scrapy爬虫:利用代理服务器爬取热门网站数据
|
3月前
|
数据采集 Web App开发 搜索推荐
突破目标网站的反爬虫机制:Selenium策略分析
突破目标网站的反爬虫机制:Selenium策略分析
|
20天前
|
数据采集 前端开发 JavaScript
被爬网站用fingerprintjs来对selenium进行反爬,怎么破?
闲暇时看到一个问题关于如何应对FingerprintJS的唯一标记技术。FingerprintJS通过收集浏览器特性如Canvas、音频、字体及插件信息生成唯一标识符,用于识别和追踪用户。常见应对策略如使用`stealth.min.js`脚本或虚拟指纹插件有局限性。高级解决方案包括: - **浏览器特征随机化**:如Canvas和音频指纹随机化,动态替换插件和字体。 - **真实用户流量模拟**:模拟自然的鼠标移动与点击、键盘输入节奏。 - **服务端策略**:使用高质量代理IP服务,如青果网络提供的代理IP,结合IP地址轮换、会话管理和合理的切换频率设置。
|
13天前
|
数据采集 Web App开发 存储
基于Python的51job(前程无忧)招聘网站数据采集,通过selenium绕过网站反爬,可以采集全国各地数十万条招聘信息
本文介绍了一个使用Python和Selenium库实现的51job(前程无忧)招聘网站数据采集工具,该工具能够绕过网站的反爬机制,自动化登录、搜索并采集全国各地的招聘信息,将数据保存至CSV文件中。
|
1月前
|
数据采集 存储 缓存
使用Scrapy进行网络爬取时的缓存策略与User-Agent管理
使用Scrapy进行网络爬取时的缓存策略与User-Agent管理
|
2月前
|
Web App开发 iOS开发 Python
经验大分享:scrapy框架爬取糗妹妹网站qiumeimei.com图片
经验大分享:scrapy框架爬取糗妹妹网站qiumeimei.com图片
16 0
|
3月前
|
数据采集 Web App开发 JavaScript
使用Selenium爬取目标网站被识别的解决之法
使用Selenium爬取目标网站被识别的解决之法
|
3月前
|
Web App开发 IDE 测试技术
实战练习:用airtest-selenium脚本爬取百度热搜标题
实战练习:用airtest-selenium脚本爬取百度热搜标题
|
3月前
|
数据采集 JavaScript 开发者
使用Scrapy有效爬取某书广告详细过程
使用Scrapy有效爬取某书广告详细过程
使用Scrapy有效爬取某书广告详细过程

热门文章

最新文章