加快网络抓取速度

时间:2016-06-14 15:32:15

标签: python html web-scraping beautifulsoup html-parsing

我有一个项目,我必须刮掉50名演员/女演员的所有评级,这意味着我必须访问并搜索3500个网页。这比预期的要长,我正在寻找一种加快速度的方法。我知道有像scrapy这样的框架,但我想在没有任何其他模块的情况下工作。是否有一种快速简便的方法来重写我的代码,或者这需要花费太多时间? 我的代码如下:

    def getMovieRatingDf(movie_links):

        counter = -1
        movie_name = []
        movie_rating = []
        movie_year = []

        for movie in movie_links.tolist()[0]:
            counter += 1

            request = requests.get('http://www.imdb.com/' + movie_links.tolist()[0][counter])
            film_soup = BeautifulSoup(request.text, 'html.parser')

            if (film_soup.find('div', {'class': 'title_wrapper'}).find('a').text).isdigit():
            movie_year.append(int(film_soup.find('div', {'class': 'title_wrapper'}).find('a').text))

            # scrap the name and year of the current film
            movie_name.append(list(film_soup.find('h1'))[0])

            try:
                movie_rating.append(float(film_soup.find('span', {'itemprop': 'ratingValue'}).text))

           except AttributeError:
                movie_rating.append(-1)
      else:
        continue

      rating_df = pd.DataFrame(data={"movie name": movie_name, "movie rating": movie_rating, "movie year": movie_year})
      rating_df = rating_df.sort_values(['movie rating'], ascending=False)

return rating_df

1 个答案:

答案 0 :(得分:8)

只需查看代码即可轻松确定主要瓶颈。它具有阻塞性。在处理当前信息之前,不要下载/解析下一页。

如果您想加快速度,请以非阻塞方式异步 。这就是Scrapy提供开箱即用的功能:

  

在这里你会注意到Scrapy的一个主要优点:请求是   异步调度和处理。 这意味着Scrapy没有   需要等待请求完成和处理,它可以发送   在此期间另一个请求或做其他事情。这也意味着   即使某些请求失败或其他请求,其他请求仍可继续   处理时发生错误。

另一种选择是从requests切换到grequests,示例代码可以在这里找到:

我们还可以在HTML解析阶段改进几件事:

  • html.parser切换到lxml(需要lxml to be installed):

    film_soup = BeautifulSoup(request.text, 'lxml')
    
  • 使用SoupStrainer 仅解析文档的相关部分

相关问题