Mechanize/BeautifulSoup を使用して、スクリプトで URL のリストを調べて開きます。
しかし、私はこのエラーが発生しています:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 718, in _set_hostport
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
httplib.InvalidURL: nonnumeric port: ''
これは、次のコード行で発生します。
page = mechanize.urlopen(req)
以下は私のコードです。私が間違っていることへの洞察はありますか?URL の多くは機能しますが、このエラー メッセージが表示されるのは特定の URL にヒットしたときなので、理由はわかりません。
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re, os
import shutil
import mechanize
import urllib2
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
mech = Browser()
linkfile = open ("links.txt")
urls = []
while 1:
url = linkfile.readline()
urls.append("%s" % linkfile.readline())
if not url:
break
for url in urls:
if "http://" or "https://" not in url:
url = "http://" + url
elif "..." in url:
elif ".pdf" in url:
#print "this is a pdf -- at some point we should save/log these"
continue
elif len (url) < 8:
continue
req = mechanize.Request(url)
req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0')
req.add_header('Accept-Language', 'Accept-Language en-US,en;q=0.5')
try:
page = mechanize.urlopen(req)
except urllib2.HTTPError, e:
print "there was an error opening the URL, logging it"
print e.code
logfile = open ("log/urlopenlog.txt", "a")
logfile.write(url + "," + "couldn't open this page" + "\n")
pass