2016-06-21 26 views
1

URLをスクラップするスクリプトを作成しました。 Linux OSでうまく動作します。しかし、Windows 7で実行しているときにhttp 503エラーが表示されます。URLに問題があります。 私はPython 2.7.11を使用しています。 助けてください。以下 はスクリプトです:場合ウェブサイトスクレイピングスクリプトはLinuxでは動作しますが、Windows 7では動作しませんか?

import sys # Used to add the BeautifulSoup folder the import path 
import urllib2 # Used to read the html document 

if __name__ == "__main__": 
    ### Import Beautiful Soup 
    ### Here, I have the BeautifulSoup folder in the level of this Python script 
    ### So I need to tell Python where to look. 
    sys.path.append("./BeautifulSoup") 
    from bs4 import BeautifulSoup 

    ### Create opener with Google-friendly user agent 
    opener = urllib2.build_opener() 
    opener.addheaders = [('User-agent', 'Mozilla/5.0')] 

    ### Open page & generate soup 
    ### the "start" variable will be used to iterate through 10 pages. 
    for start in range(0,1000): 
     url = "http://www.google.com/search?q=site:theknot.com/us/&start=" + str(start*10) 
     page = opener.open(url) 
     soup = BeautifulSoup(page) 

     ### Parse and find 
     ### Looks like google contains URLs in <cite> tags. 
     ### So for each cite tag on each page (10), print its contents (url) 
    file = open("parseddata.txt", "wb") 
    for cite in soup.findAll('cite'): 
       print cite.text 
       file.write(cite.text+"\n") 
       # file.flush() 
       # file.close() 

は、Windows 7でそれを実行し、cmdは問題を記載http503エラーがURLであるスロー。 URLはLinux OSで正常に動作します。 URLが実際に間違っている場合は、代替案を提案してください。

+0

これは関係ありませんが、10個のリクエストを生成する代わりに、検索URLの最後に '&num = 100'を追加して一度に100個の結果を得ることができますか? – spectras

+3

接続が多すぎるため、GoogleがあなたのIPをブロックしている可能性があります。 – Barmar

+0

実際、非常に良い点@バーマール。自動化されたクエリがGoogleの利用規約に違反していると、あなたをブロックする可能性があります。それは彼のWindowsからではなく、彼のLinuxボックスから一貫して起こることは奇妙です。 – spectras

答えて

0

Windows上のPython 2.7.2では、カスタムUser-agentヘッダーを送信するたびに、urllib2はそのヘッダーを送信しません。 (出典:https://stackoverflow.com/a/8994498/6479294)。

だからではなく、Windowsのurllib2のの要求を使用して検討する必要があります

import requests 
# ... 
page = requests.get(url) 
soup = BeautifulSoup(page.text) 
# etc... 

EDIT:また作られている非常に良い点は、GoogleがあなたのIPをブロックすることができるということである - 彼らは本当に好きではありませんボットは100個の奇妙なリクエストを順番に作ります。

+1

リクエストありがとうございました。 –

関連する問題