Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python urllib2/BeautifulSoup获取一页的速度似乎很慢_Python_Beautifulsoup_Urllib2 - Fatal编程技术网

Python urllib2/BeautifulSoup获取一页的速度似乎很慢

Python urllib2/BeautifulSoup获取一页的速度似乎很慢,python,beautifulsoup,urllib2,Python,Beautifulsoup,Urllib2,我正在学习如何从网上获取数据。为此,我使用python2.7、urllib2和BeautifulSoup(使用python2.7,因为这是我在工作中使用的版本,所以不想混淆语法…) 到目前为止,我有一个单一的测试,它只是获取一个页面来获取一些信息 源url: 我现在得到了球队名称、年份、教练和记录 我没有抓取网页的经验,但仅仅抓取一个网页对我来说太长了 我的时间很紧 D:\miniconda3\envs\tes1\python.exe C:/Users/my_name/PycharmProjec

我正在学习如何从网上获取数据。为此,我使用python2.7、urllib2和BeautifulSoup(使用python2.7,因为这是我在工作中使用的版本,所以不想混淆语法…)

到目前为止,我有一个单一的测试,它只是获取一个页面来获取一些信息

源url:

我现在得到了球队名称、年份、教练和记录

我没有抓取网页的经验,但仅仅抓取一个网页对我来说太长了

我的时间很紧

D:\miniconda3\envs\tes1\python.exe C:/Users/my_name/PycharmProjects/testing/web_scraping/bb_ref/my_test_web_classes.py
urlopen in 1.4240 secs
generate res in 2.8070 secs
Finished get_page in 4.2310 secs
Finished get_team_info in 0.0000 secs
Team: Toronto Raptors   Coach: Nick Nurse   Year: 2018-19   Record: 58-24   
Process finished with exit code 0
我们可以看到所有的时间都花在获取信息上。我的测试是

from web_classes import WebPage
from bb_ref_team import Team


page_bs = WebPage.get_page('https://www.basketball-reference.com/teams/TOR/2019.html', output='bs')
team_info = Team.get_team_info(page_bs)
team = Team(name=team_info['team'],
            coach=team_info['coach'],
            year=team_info['year'],
            record=team_info['record'])
print team
获取页面的类是

from bs4 import BeautifulSoup
from urllib2 import urlopen
from urllib2 import HTTPError
from urllib2 import URLError
from decorators import timer
import time


class WebPage:
    def __init__(self, url):
        self.url = url

    @staticmethod
    @timer
    def get_page(url, output='text'):
        try:
            start_time = time.time()
            html = urlopen(url)
            run_time = time.time() - start_time
            print ' urlopen in {:.4f} secs'.format(run_time)
        except HTTPError as e:
            print e
            return None
        except URLError as e:
            print e
            return None
        else:
            if output == 'text':
                start_time = time.time()
                res = html.read()
                run_time = time.time() - start_time
                print ' generate res in {:.4f} secs'.format(run_time)
                return res
            elif output == 'bs':
                start_time = time.time()
                res = BeautifulSoup(html, 'html.parser')
                run_time = time.time() - start_time
                print ' generate res in {:.4f} secs'.format(run_time)
                return res
解析BeautifulSoup实例以创建my Team实例的类是

from bb_ref_data import Data
from decorators import timer
import re


class Team(Data):
    def __init__(self, name, coach, year, record):
        super(Team, self).__init__()
        self.data['year'] = year
        self.data['name'] = name
        self.data['coach'] = coach
        self.data['record'] = record  # win_game-lost_game

    def __str__(self):
        return "Team: %s\tCoach: %s\tYear: %s\tRecord: %s\t" % (self.data['name'],
                                                                self.data['coach'],
                                                                self.data['year'],
                                                                self.data['record'])

    @staticmethod
    @timer
    def get_team_info(page):
        """
        return team page information
        :param page: BeautifulSoup page object
        :return:
        """
        summary = page.find('div', {'data-template': 'Partials/Teams/Summary'})
        title = summary.h1.find_all('span')
        year = title[0].get_text()
        team = title[1].get_text()
        infos = summary.find_all('p')
        rec = re.search(r'(\d+-\d+)', infos[0].get_text()).group()
        coach = re.search(r'Coach: (\w+( \w+)*)', infos[1].get_text()).group(1)
        return {'team': team, 'coach': coach, 'year': year, 'record': rec}
Team类继承自下面的类,该类只是一个字典

class Data(object):
    def __init__(self):
        self.data = {}

    def __copy__(self):
        new = type(self)
        new.data = self.data.copy()
        return new
我的装饰定时器功能是:

def timer(func):
    """Print the runtime of the decorated function"""
    @functools.wraps(func)
    def wrapper_timer(*args, **kwargs):
        start_time = time.time()    # 1
        value = func(*args, **kwargs)
        end_time = time.time()      # 2
        run_time = end_time - start_time    # 3
        print "Finished {} in {:.4f} secs".format(func.__name__, run_time)
        return value
    return wrapper_timer
你觉得它很长吗?所以花3秒来生成一个BeautifulSoup对象,我能做些什么来加速它

谢谢你的意见

祝你周末愉快

注意: 我对ULSOUP和lxml做了一个小的基准测试,后者显示了更好的计时。 对于每个我运行了100次单一测试的对象(urlopen+生成表示网页的对象)

为了美丽的乌苏,我有

mean: 2.37027
std: 0.4379433948582853
var: 0.1917944171
对于lxml,我有

mean: 2.27229
std: 0.3342248433315513
var: 0.11170624589999999

您的
团队中发生了什么
类,您也可以提供这些代码吗?您请求的网页的HTML源代码看起来有些奇怪,但一般来说,我不认为beautifulsoup会成为性能瓶颈。我在原始帖子中添加了它。谢谢,我用Python3在jupyter笔记本上尝试了你的代码,但不幸的是,我也遇到了同样的性能问题。你有没有试过,比如说?还有一些关于改进“我做了一个小工作台”中性能的更多提示,即“我做了一个小工作台”优化了“我做了一个小工作台”,而“我做了一个小工作台”优化了“我做了一个小工作台”。我把这些数字放在原来的帖子里。我想我会选择lxml在你的
团队
课程中发生了什么,你能同时提供这些代码吗?您请求的网页的HTML源代码看起来有些奇怪,但一般来说,我不认为beautifulsoup会成为性能瓶颈。我在原始帖子中添加了它。谢谢,我用Python3在jupyter笔记本上尝试了你的代码,但不幸的是,我也遇到了同样的性能问题。你有没有试过,比如说?还有一些关于改进“我做了一个小工作台”中性能的更多提示,即“我做了一个小工作台”优化了“我做了一个小工作台”,而“我做了一个小工作台”优化了“我做了一个小工作台”。我把这些数字放在原来的帖子里。我想我会选择lxml