【问题标题】:Error while using URLLIB in Python 2.7在 Python 2.7 中使用 URLLIB 时出错
【发布时间】: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

【问题讨论】:

标签: python python-2.7 urllib


【解决方案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}

即:为我工作。

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多