python - Mechanize 和 Beautifulsoup httplib.InvalidURL : nonnumeric port: '' (Python) 错误

标签 python beautifulsoup mechanize

我正在浏览一个 URL 列表,并使用我的脚本打开它们,使用 Mechanize/BeautifulSoup。

但是我收到此错误:

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

最佳答案

我认为这段代码

if "http://" or "https://" not in url: 

不是在做你想做的(或者你认为它会做的)。
if "http://"

将始终评估为真,因此您的 URL 永远不会前缀。
您需要将其重写(例如)为:
if "https://" not in url and "http://" not in url:

此外,现在我开始测试你的作品:
urls = []
while 1:
    url = linkfile.readline()
    urls.append("%s" % linkfile.readline())
    if not url:
        break

这实际上可以确保您的 URL 文件被不正确地读取,并且每第二行都被读入,您可能希望读取:
urls = []
while 1:
    url = linkfile.readline()
    if not url:
        break
    urls.append("%s" % url)

原因是 - 您调用 linkfile.readline()两次,强制它读取 2 行并仅将每 2 行保存到您的列表中。

另外,您想要 if子句在附加之前,以防止在列表末尾出现空条目。

但是您的特定 URL 示例对我有用。更多,我可能需要你的链接文件。

关于python - Mechanize 和 Beautifulsoup httplib.InvalidURL : nonnumeric port: '' (Python) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14111919/

相关文章:

python - Tkinter 的 overrideredirect 阻止了 Mac 和 Linux 中的某些事件

python - 如何在python中停止这个while循环

heroku - Mechanize + Sinatra + Heroku : App crashed

python - 类型错误 : Required argument 'mat' (pos 2) not found

python - 这个 Python 字符串中的 {0} 是什么意思?

python - 使用请求和 Beautifulsoup 在页面中查找文本(使用 CSS)

python - Pandas:无法从 DataFrame 列中剥离 HTML 标签

python - 抓取包含::之前的网页

http-status-code-404 - Mechanize/Ruby读取404页面源代码

Perl Mechanize 响应只有 "<HTML></HTML>"和 https