【问题标题】:Scraping with Scrapy and Selenium用 Scrapy 和 Selenium 进行刮擦
【发布时间】:2013-09-21 02:11:06
【问题描述】:

我有一个爬虫爬虫,它爬取一个通过页面上的 javascript 重新加载内容的网站。为了移动到下一页进行抓取,我一直在使用 Selenium 点击网站顶部的月份链接。

问题是,即使我的代码按预期移动通过每个链接,蜘蛛只是抓取第一个月(9 月)的月数数据并返回此重复数据。

我该如何解决这个问题?

from selenium import webdriver

class GigsInScotlandMain(InitSpider):
        name = 'gigsinscotlandmain'
        allowed_domains = ["gigsinscotland.com"]
        start_urls = ["http://www.gigsinscotland.com"]


    def __init__(self):
        InitSpider.__init__(self)
        self.br = webdriver.Firefox()

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        self.br.get(response.url)
        time.sleep(2.5)
        # Get the string for each month on the page.
        months = hxs.select("//ul[@id='gigsMonths']/li/a/text()").extract()

        for month in months:
            link = self.br.find_element_by_link_text(month)
            link.click()
            time.sleep(5)

            # Get all the divs containing info to be scraped.
            listitems = hxs.select("//div[@class='listItem']")
            for listitem in listitems:
                item = GigsInScotlandMainItem()
                item['artist'] = listitem.select("div[contains(@class, 'artistBlock')]/div[@class='artistdiv']/span[@class='artistname']/a/text()").extract()
                #
                # Get other data ...
                #
                yield item

【问题讨论】:

    标签: python selenium scrapy


    【解决方案1】:

    问题是您正在重用为初始响应定义的HtmlXPathSelector。从selenium浏览器重新定义source_code

    ...
    for month in months:
        link = self.br.find_element_by_link_text(month)
        link.click()
        time.sleep(5)
    
        hxs = HtmlXPathSelector(self.br.page_source)
    
        # Get all the divs containing info to be scraped.
        listitems = hxs.select("//div[@class='listItem']")
    ...
    

    【讨论】:

    • 非常有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2019-05-09
    • 2018-07-24
    • 2019-03-09
    • 2022-01-02
    • 2015-04-02
    相关资源
    最近更新 更多