【问题标题】:python scraping [closed]python抓取[关闭]
【发布时间】:2012-08-28 08:06:24
【问题描述】:

我正在尝试获取餐馆的名称、地址和电话号码。

我的代码一直卡在第二个定义中。第一个 def 工作正常。我不知道为什么,因为我无法识别任何错误。循环只是没有通过。

如果我犯了明显的错误,我希望有人发表评论。

谢谢

from urllib2 import urlopen
from csv import writer

def get_urls_of_restaurant():
    list_urls = []
    n = 0
    nn = 0
    for i in range(6):
        url = urlopen('http://www.go.co.tz/index.php/restaurants/masaki?start=' +     str(nn)).readlines() #open URL whis lists restaurants
        while n < len(url):
            if '<h2 class="contentheading">' in url[n]:
                list_urls.append(url[n+1].split('"')[1])
            n += 1
        n = 0
        nn += 3
    list_urls.reverse()
    print "Geting urls done! Get %s" %len(list_urls) + ' urls.'
    return list_urls

def open_url_and_write_data(list_urls):
    n = len(list_urls)-1
    csv_file = open('restdar_guide.csv', 'wb')
    file_writer = writer(csv_file, delimiter=';')
    file_writer.writerow(['Name'] + ['address'] + ['phone'])
    while n >= 0:
        print 'Reading %s' % str(int(len(list_urls))-n) + " element of %s" % len(list_urls) + " element's..."
        url = urlopen('http://www.go.co.tz' + list_urls[n]).readlines()
        num_str = 0
        list_write = []
        while num_str < len(url):
            if '<title>' in url[num_str]:
                list_write.append(url[num_str].split('<')[0][7:])
            if 'Location:</strong>' in url[num_str]:
                list_write.append(url[num_str].split('<')[1][9:])
            else:
                list_write.append('unknown')
            if '<li><strong>Tel:</strong>' in url[num_str]:
                list_write.append(url[num_str].split('<')[2][10:])
            else:
                list_write.append('unknown')
            file_writer.writerow([list_write[0]] + [list_write[1]] + [list_write[2]])
        n -= 1
    csv_file.close()
    print 'Done!'

list_urls = get_urls_of_restaurant()
open_url_and_write_data(list_urls)

【问题讨论】:

  • 就在您认为使用正则表达式解析 HTML 是最糟糕的想法时,有人出现并使用 split 和切片来解析 HTML。 颤抖
  • 如何使用 HTML 解析器,例如 html5lib、BeautifulSoup、lxml 等?

标签: python web-scraping


【解决方案1】:

BeautifulSoup 可能会让您的生活更轻松。

【讨论】:

    【解决方案2】:

    好吧,如果你中止程序,你只会得到 KeyboardInterrupt 错误。根据时间的不同,您可能会在该 while 循环中的任何行上发生错误 - 无论您最终崩溃并中止时它正在执行的指令是什么。

    您的程序因此进入非终止循环:

    num_str = 0
    ...
    while num_str < len(url): 
    

    您永远不会更改 num_str 的值,因此对于任何大于 0 的 len(url) 值,这等效于 while True:。顺便说一句,这是 for 循环的好地方。

    也就是说,正如其他人所指出的,这在很大程度上是进行 HTML 解析/网络抓取的非最佳方式。有许多可用的抓取实用程序和 HTML 解析器,我认为您最好这样做。

    【讨论】:

    • 感谢您指出我的愚蠢错误。难怪它会无限循环!
    【解决方案3】:

    n = len(list_urls)-1”的缩进好像太远了,试着和下一行对齐。

    【讨论】:

    • 那是评论中的错字。问题仍然存在。这是我在中止程序后得到的错误:^CTraceback(最后一次调用):文件“restaurants_darguide.py”,第 66 行,在 open_url_and_write_data(list_urls) 文件“restaurants_darguide.py”,第 56 行,在open_url_and_write_data if '
    • Tel:' in url[num_str]: KeyboardInterrupt
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签