6

当我听到一些关于线程和 urllib3 的好消息时,我正在寻找一种优化我的代码的方法。显然,人们不同意哪种解决方案是最好的。

下面我的脚本的问题是执行时间:太慢了!

第 1 步:我获取此页面 http://www.cambridgeesol.org/institutions/results.php?region=Afghanistan&type=&BULATS=on

第 2 步:我用 BeautifulSoup 解析页面

第 3 步:我将数据放入 Excel 文档中

第 4 步:我对列表中的所有国家(大列表)一次又一次地重复(我只是将 url 中的“阿富汗”更改为另一个国家)

这是我的代码:

ws = wb.add_sheet("BULATS_IA") #We add a new tab in the excel doc
    x = 0 # We need x and y for pulling the data into the excel doc
    y = 0
    Countries_List = ['Afghanistan','Albania','Andorra','Argentina','Armenia','Australia','Austria','Azerbaijan','Bahrain','Bangladesh','Belgium','Belize','Bolivia','Bosnia and Herzegovina','Brazil','Brunei Darussalam','Bulgaria','Cameroon','Canada','Central African Republic','Chile','China','Colombia','Costa Rica','Croatia','Cuba','Cyprus','Czech Republic','Denmark','Dominican Republic','Ecuador','Egypt','Eritrea','Estonia','Ethiopia','Faroe Islands','Fiji','Finland','France','French Polynesia','Georgia','Germany','Gibraltar','Greece','Grenada','Hong Kong','Hungary','Iceland','India','Indonesia','Iran','Iraq','Ireland','Israel','Italy','Jamaica','Japan','Jordan','Kazakhstan','Kenya','Kuwait','Latvia','Lebanon','Libya','Liechtenstein','Lithuania','Luxembourg','Macau','Macedonia','Malaysia','Maldives','Malta','Mexico','Monaco','Montenegro','Morocco','Mozambique','Myanmar (Burma)','Nepal','Netherlands','New Caledonia','New Zealand','Nigeria','Norway','Oman','Pakistan','Palestine','Papua New Guinea','Paraguay','Peru','Philippines','Poland','Portugal','Qatar','Romania','Russia','Saudi Arabia','Serbia','Singapore','Slovakia','Slovenia','South Africa','South Korea','Spain','Sri Lanka','Sweden','Switzerland','Syria','Taiwan','Thailand','Trinadad and Tobago','Tunisia','Turkey','Ukraine','United Arab Emirates','United Kingdom','United States','Uruguay','Uzbekistan','Venezuela','Vietnam']
    Longueur = len(Countries_List)



    for Countries in Countries_List:
        y = 0

        htmlSource = urllib.urlopen("http://www.cambridgeesol.org/institutions/results.php?region=%s&type=&BULATS=on" % (Countries)).read() # I am opening the page with the name of the correspondant country in the url
        s = soup(htmlSource)
        tableGood = s.findAll('table')
        try:
            rows = tableGood[3].findAll('tr')
            for tr in rows:
                cols = tr.findAll('td')
                y = 0
                x = x + 1
                for td in cols:
                    hum =  td.text
                    ws.write(x,y,hum)
                    y = y + 1
                    wb.save("%s.xls" % name_excel)

        except (IndexError):
            pass

所以我知道一切都不完美,但我期待在 Python 中学习新事物!该脚本非常慢,因为 urllib2 并没有那么快,而且 BeautifulSoup。对于汤的事情,我想我真的不能让它变得更好,但是对于 urllib2,我没有。

编辑 1: 多处理对 urllib2 没用? 对我来说似乎很有趣。你们如何看待这个潜在的解决方案?!

# Make sure that the queue is thread-safe!!

def producer(self):
    # Only need one producer, although you could have multiple
    with fh = open('urllist.txt', 'r'):
        for line in fh:
            self.queue.enqueue(line.strip())

def consumer(self):
    # Fire up N of these babies for some speed
    while True:
        url = self.queue.dequeue()
        dh = urllib2.urlopen(url)
        with fh = open('/dev/null', 'w'): # gotta put it somewhere
            fh.write(dh.read())

编辑 2: URLLIB3 谁能告诉我更多关于它的事情?

对多个请求(HTTPConnectionPool 和 HTTPSConnectionPool)重复使用相同的套接字连接(带有可选的客户端证书验证)。 https://github.com/shazow/urllib3

至于我为不同的页面请求同一个网站 122 次,我想重用相同的套接字连接可能很有趣,我错了吗?不能更快吗?...

http = urllib3.PoolManager()
r = http.request('GET', 'http://www.bulats.org')
for Pages in Pages_List:
    r = http.request('GET', 'http://www.bulats.org/agents/find-an-agent?field_continent_tid=All&field_country_tid=All&page=%s' % (Pages))
    s = soup(r.data)
4

3 回答 3

9

考虑使用类似workerpool的东西。参考Mass Downloader示例,结合urllib3看起来像:

import workerpool
import urllib3

URL_LIST = [] # Fill this from somewhere

NUM_SOCKETS = 3
NUM_WORKERS = 5

# We want a few more workers than sockets so that they have extra
# time to parse things and such.

http = urllib3.PoolManager(maxsize=NUM_SOCKETS)
workers = workerpool.WorkerPool(size=NUM_WORKERS)

class MyJob(workerpool.Job):
    def __init__(self, url):
       self.url = url

    def run(self):
        r = http.request('GET', self.url)
        # ... do parsing stuff here


for url in URL_LIST:
    workers.put(MyJob(url))

# Send shutdown jobs to all threads, and wait until all the jobs have been completed
# (If you don't do this, the script might hang due to a rogue undead thread.)
workers.shutdown()
workers.wait()

您可能会从 Mass Downloader 示例中注意到,有多种方法可以做到这一点。我选择这个特殊的例子只是因为它不那么神奇,但其他任何策略也是有效的。

免责声明:我是 urllib3 和 workerpool 的作者。

于 2012-04-24T04:41:29.673 回答
2

我不认为 urllib 或 BeautifulSoup 很慢。我在本地机器上运行您的代码,并使用修改后的版本(删除了 excel 内容)。打开连接、下载内容、解析内容并将其打印到一个国家/地区的控制台大约需要 100 毫秒。

10ms 是 BeautifulSoup 解析内容并打印到每个国家/地区的控制台所花费的总时间。这已经足够快了。

我不相信使用 Scrappy 或 Threading 可以解决问题。因为问题是期望它会很快。

欢迎来到 HTTP 的世界。有时会很慢,有时会很快。连接速度慢的几个原因

  • 因为服务器处理您的请求(有时返回 404)
  • DNS解析,
  • HTTP握手,
  • 您的 ISP 的连接稳定性,
  • 你的带宽速率,
  • 丢包率

ETC..

不要忘记,您正在尝试向服务器发出 121 个 HTTP 请求,但您不知道他们拥有什么样的服务器。他们也可能因为随后的呼叫而禁止您的 IP 地址。

看看请求库。阅读他们的文档。如果您这样做是为了更多地学习 Python,请不要直接跳入 Scrapy。

于 2012-04-22T08:36:52.863 回答
0

大家好,

一些来自问题的消息!我找到了这个脚本,它可能很有用!我实际上正在测试它并且很有希望(6.03 运行下面的脚本)。

我的想法是找到一种将其与 urllib3 混合的方法。实际上,我多次在同一主机上提出请求。

每当您请求同一主机时,PoolManager 都会为您重用连接。这应该涵盖大多数场景而不会显着降低效率,但您始终可以下拉到较低级别的组件以进行更精细的控制。(urrlib3 文档网站)

无论如何,这似乎很有趣,如果我还看不到如何混合这两个功能(urllib3 和下面的线程脚本),我想这是可行的!:-)

非常感谢您花时间帮我解决这个问题,它闻起来很香!

import Queue
import threading
import urllib2
import time
from bs4 import BeautifulSoup as BeautifulSoup



hosts = ["http://www.bulats.org//agents/find-an-agent?field_continent_tid=All&field_country_tid=All", "http://www.bulats.org//agents/find-an-agent?field_continent_tid=All&field_country_tid=All&page=1", "http://www.bulats.org//agents/find-an-agent?field_continent_tid=All&field_country_tid=All&page=2", "http://www.bulats.org//agents/find-an-agent?field_continent_tid=All&field_country_tid=All&page=3", "http://www.bulats.org//agents/find-an-agent?field_continent_tid=All&field_country_tid=All&page=4", "http://www.bulats.org//agents/find-an-agent?field_continent_tid=All&field_country_tid=All&page=5", "http://www.bulats.org//agents/find-an-agent?field_continent_tid=All&field_country_tid=All&page=6"]

queue = Queue.Queue()
out_queue = Queue.Queue()

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()

class DatamineThread(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, out_queue):
        threading.Thread.__init__(self)
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            chunk = self.out_queue.get()

            #parse the chunk
            soup = BeautifulSoup(chunk)
            #print soup.findAll(['table'])

            tableau = soup.find('table')
        rows = tableau.findAll('tr')
        for tr in rows:
            cols = tr.findAll('td')
            for td in cols:
                    texte_bu = td.text
                    texte_bu = texte_bu.encode('utf-8')
                    print texte_bu

            #signals to queue job is done
            self.out_queue.task_done()

start = time.time()
def main():

    #spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue, out_queue)
        t.setDaemon(True)
        t.start()

    #populate queue with data
    for host in hosts:
        queue.put(host)

    for i in range(5):
        dt = DatamineThread(out_queue)
        dt.setDaemon(True)
        dt.start()


    #wait on the queue until everything has been processed
    queue.join()
    out_queue.join()

main()
print "Elapsed Time: %s" % (time.time() - start)
于 2012-04-23T08:52:59.550 回答