2012-03-27 6 views
1

属性をスクラップしたいURLのリストがあります。初心者からPythonへ、だから申し訳ありません。 Windows 7,64ビット。 Python 3.2。Python - HTTPResponseオブジェクトに対するURLの受け渡し

次のコードが機能します。 pblistは、キー 'short_url'を含むdictsで構成されたリストです。

次のコードは、たとえば、コードがBeautifulSoupオブジェクトにhead属性とtitle属性を持たないと主張しています。

for j in pblist[0:10]: 
     base_url = j['short_url'] 
     page = urllib.request.urlopen(base_url) 
     if hasattr(BeautifulSoup(page), 'head') and \ 
      hasattr(BeautifulSoup(page).head, 'title'): 
       print("Has head, title attributes.") 
       try: 
        j['title'] = BeautifulSoup(urllib.request.urlopen(base_url)).head.title.string.encode('utf-8') 
       except AttributeError: 
        print("Encountered attribute error on page, ", base_url) 
        j['title'] = "Attribute error." 
        pass 

なぜですか? BeautifulSoup内のurllib.request.urlopenにURLを渡して、urllib.request.urlopenが返すHTTPResponseオブジェクトを渡すことの違いは何ですか?

答えて

0

urlopen()によって提供されるレスポンスは、ファイルのようなオブジェクトです。つまり、デフォルトでイテレータのように動作します。つまり、一度読み込んだら、それ以上データを取得しません明示的にリセットしない限り)。

したがって、第2のバージョンでは、BeautifulSoup(page)の最初の呼び出しはすべてpageのうちのすべてのデータを読み取り、その後の呼び出しには読み込むデータがそれ以上ありません。

代わりに、何を行う可能性はこれです:

page = urllib.request.urlopen(base_url) 
page_content = page.read() 
# ... 
BeautifulSoup(page_content) 
# ... 
BeautifulSoup(page_content) 

それでも、それは非効率的なの一種です。代わりに、単にBeautifulSoupオブジェクトを作成して渡すのはなぜですか?単一スープオブジェクトを使用するように変更

page = urllib.request.urlopen(base_url) 
soup = BeautifulSoup(page) 
# ... 
# do something with soup 
# ... 
# do something with soup 

あなたのコード、:

for j in pblist[0:10]: 
     base_url = j['short_url'] 
     page = urllib.request.urlopen(base_url) 
     soup = BeautifulSoup(page) 
     if hasattr(soup, 'head') and \ 
      hasattr(soup.head, 'title'): 
       print("Has head, title attributes.") 
       try: 
        j['title'] = soup.head.title.string.encode('utf-8') 
       except AttributeError: 
        print("Encountered attribute error on page, ", base_url) 
        j['title'] = "Attribute error." 
        pass 
+0

それを手に入れました。ありがとうアンバー。 – Zack

関連する問題