scrapy+selenium爬取UC頭條網(wǎng)站

Scrapy是Python優(yōu)秀的爬蟲(chóng)框架,selenium是非常好用的自動(dòng)化WEB測(cè)試工具,兩者結(jié)合可以非常容易對(duì)動(dòng)態(tài)網(wǎng)頁(yè)進(jìn)行爬蟲(chóng)。
本文的需求是抓取UC頭條各個(gè)板塊的內(nèi)容。UC頭條(https://news.uc.cn/ )網(wǎng)站沒(méi)有提供搜索入口,只能每個(gè)板塊的首頁(yè)向下滾動(dòng)鼠標(biāo)加載更多。要對(duì)這樣的網(wǎng)站進(jìn)行檢索,抓取其內(nèi)容,采用一般的scrapy請(qǐng)求方式,每次只能獲取最新的10條數(shù)據(jù),分析其JS請(qǐng)求,發(fā)現(xiàn)參數(shù)過(guò)于復(fù)雜,沒(méi)有規(guī)律。如果想獲取更多數(shù)據(jù),則需要采用模擬瀏覽器的方法,這時(shí)候selenium就派上用場(chǎng)了。

image

1,定義spider

模擬從百度搜索進(jìn)入,這個(gè)步驟可以省略,主要為了跳到parse函數(shù)

class UCTouTiaoSpider(VideoBaseSpider):
    name = "uctoutiao_spider"
    df_keys = ['人物', '百科', '烏鎮(zhèn)']
 
 
    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函數(shù)

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/"]
      
    # 啟動(dòng)瀏覽器,這里用的火狐,如果在linux環(huán)境下可以用PhantomJS,穩(wěn)定性稍微差點(diǎn),有內(nèi)存泄露的風(fēng)險(xiǎn)。
    driver = webdriver.Firefox()
    for url in urls:
        try:
            print(url)
            driver.get(url)
            #模擬鼠標(biāo)滾到底部(加載100條數(shù)據(jù))
            for _ in range(10):
                driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
                driver.implicitly_wait(10)  # 隱性等待,最長(zhǎng)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()

真正的實(shí)現(xiàn)部分比較簡(jiǎn)單,幾句代碼就搞定了。

附:

selenium使用實(shí)例

1,切換焦點(diǎn)至新窗口

在頁(yè)面上點(diǎn)擊一個(gè)button, 然后打開(kāi)了一個(gè)新的window, 將當(dāng)前IWebDriver的focus切換到新window,使用IWebDriver.SwitchTo().Window(string windowName)。

例如, 我點(diǎn)擊按鈕以后彈出一個(gè)名字叫做"Content Display"的window, 要切換焦點(diǎn)到新窗口的方法是, 首先,獲得新window的window name, 大家不要誤以為page tile就是window name 哦, 如果你使用driver.SwitchTo().Window("Content Display")是找不到window name 叫做"Content Display"的窗口的, 其實(shí)Window Name 是一長(zhǎng)串?dāng)?shù)字,類似“59790103-4e06-4433-97a9-b6e519a84fd0”。

要正確切換到"Content Display"的方法是:

  1. 獲得當(dāng)前所有的WindowHandles。

  2. 循環(huán)遍歷到所有的window, 查找window.title與"Content Display"相符的window返回。

for handle in dr.window_handles:
    dr.switch_to.window(handle)
    print dr.title
    if len(dr.title) == '目標(biāo)窗口標(biāo)題':
        break

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

2 ,移至底部

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

3,移動(dòng)至指定元素

某些按鈕點(diǎn)擊時(shí)必須可見(jiàn),于是要把屏幕移動(dòng)到按鈕可見(jiàn)的區(qū)域

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

參考:
Python selenium —— 一定要會(huì)用selenium的等待,三種等待方式解讀

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容