在 Python 2.7 中使用 URLLIB 时出错

Posted

技术标签:

【中文标题】在 Python 2.7 中使用 URLLIB 时出错【英文标题】:Error while using URLLIB in Python 2.7 【发布时间】:2017-04-13 02:02:39 【问题描述】:

导入 urllib 从 bs4 导入 BeautifulSoup 重新导入

总和 = 0

html = urllib.urlopen('http://python-data.dr-chuck.net/comments_338391.html').read()

汤 = BeautifulSoup(html)

标签 = 汤('span')

对于标签中的 lne: lne = str(lne) 数据 = re.findall('[0-9]+',lne) 数据[0] = int(数据[0]) sumt = sumt + 数据[0]

打印总和

错误:

IOError: [Errno socket error] [Errno 11004] getaddrinfo failed

【问题讨论】:

"getaddrinfo failed", what does that mean?的可能重复 【参考方案1】:

请注意,urllib.urlopen 已弃用;你应该使用urllib2.urlopen

无论如何,对我来说两个版本都可以正常工作。

import urllib2
import re

if __name__ == '__main__':
    url = 'http://python-data.dr-chuck.net/comments_338391.html'
    comments = 
    pattern = re.compile('<tr><td>(?P<name>.+?)</td>.+?class="comments">(?P<count>\d+)</span>.+?')
    for line in urllib2.urlopen(url).read().split('\n'):
        m = pattern.match(line)
        if m:
            comments[m.group('name')] = int(m.group('count'))
    print(comments)

产量:

'Caidan': 28, 'Haylie': 59, 'Fikret': 43, 'Tabbitha': 54, 'Rybecca': 70, 'Pearl': 45, 'Kiri': 72, 'Storm': 66, 'Kelum': 55, 'Elisau': 30, 'Lexi': 70, 'Cobain': 2, 'Theodore': 36, 'Ammer': 26, 'Carris': 87, 'Fion': 10, 'Derick': 28, 'Shalamar': 98, 'Adil': 93, 'Wasif': 54, 'Yasin': 78, 'Mhyren': 92, 'Kodi': 75, 'Nikela': 98, 'Lorena': 76, 'Seth': 68, 'Lillia': 91, 'Nitya': 26, 'Tigan': 73, 'Jaii': 11, 'Kamran': 74, 'Arianna': 12, 'Mercedes': 92, 'Gregory': 40, 'Umaima': 83, 'Rhylee': 26, 'Kaia': 91, 'Hamid': 33, 'Lucien': 5, 'Zacharias': 92, 'Abir': 35, 'Teejay': 51, 'Muir': 43, 'Hena': 84, 'Alanas': 16, 'Lybi': 91, 'Atiya': 87, 'Kayleb': 7, 'Fletcher': 87, 'Lisandro': 78

即:为我工作。

【讨论】:

以上是关于在 Python 2.7 中使用 URLLIB 时出错的主要内容,如果未能解决你的问题,请参考以下文章

使用 urllib2 登录网站 - Python 2.7

Python 2.7 urllib.urlretrieve 未知 url 类型 https

AWS Elastic Beanstalk 500 错误 (Django) - Python-urllib/2.7 & 静态文件错误

1.Urllib2模块使用

urllib与urllib2的学习总结

python urllib2.urlopen(url).read()乱码