【问题标题】:urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>urllib.error.URLError: <urlopen 错误 [Errno -2] 名称或服务未知>
【发布时间】:2015-09-29 23:06:57
【问题描述】:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import random
import re

random.seed(datetime.datetime.now())

def getLinks(articleUrl):
    html = urlopen("http://en.wikipedia.org"+articleUrl)
    bsObj = BeautifulSoup(html)
    return bsObj.find("div", {"id":"bodyContent"}).findAll("a",href = re.compile("^(/wiki/)((?!:).)*$"))

getLinks('http://en.wikipedia.org')

操作系统是 Linux。上面的脚本吐出一个“urllib.error.URLError:”。查看了我在 google 上找到的许多解决此问题的尝试,但没有一个解决了我的问题(尝试的解决方案包括更改 env 变量并将名称服务器 8.8.8.8 添加到我的 resolv.conf 文件中)。

【问题讨论】:

  • 除了你还没有弄清楚函数的第一行在做什么吗?
  • @IgnacioVazquez-Abrams 哦,天哪,我现在觉得自己很愚蠢。在编写其余部分之前,我只是将它放在那里以“测试”脚本,但是当我用实际的维基百科文章尝试它时,它停止给出 URL 错误。谢谢!
  • articleUrl 的值是多少?

标签: python urllib


【解决方案1】:

您应该使用有效的网址调用getLinks()

>>> getLinks('/wiki/Main_Page')

此外,在您的函数中,您还应该调用.read() 来获取响应内容,然后再将其传递给BeautifulSoup

>>> html = urlopen("http://en.wikipedia.org" + articleUrl).read()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多