2011-09-19 37 views
12

Tôi rất mới với python. Rất mới. Tôi sao chép sau đây từ một hướng dẫnTênError: tên 're' không được xác định

#!/usr/bin/python 
import re 
from urllib import urlopen 
from BeautifulSoup import BeautifulSoup 

webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read 

patFinderTitle = re.compile('<title>(.*)</title>') 

patFinderLink = re.compile('<link rel.*href="(.*)"/>') 

findPatTitle = re.findall(patFinderTitle,webpage) 

findPatLink = re.findall(patFinderLink,webpage) 

listIterator = [] 
listIterator[:] = range(2,16) 

for i in listIterator: 
    print findPatTitle[i] 
    print findPatLink[i] 
    print "\n" 

tôi nhận được lỗi:

Traceback (most recent call last): 
    File "test.py", line 8, in <module> 
    patFinderTitle = re.compile('<title>(.*)</title>') 
NameError: name 're' is not defined 

Tôi đang làm gì sai?

Edit: Tôi thêm import re nhưng bây giờ nhận được như sau:

File "/scripts/_prod/test.py", line 13, in <module> 
    findPatTitle = re.findall(patFinderTitle,webpage) 
    File "/usr/lib64/python2.6/re.py", line 177, in findall 
    return _compile(pattern, flags).findall(string) 
TypeError: expected string or buffer 
+0

Bạn đã sao chép hướng dẫn này từ đâu? Nó có nhiều lỗi. – Johnsyweb

+0

http://www.youtube.com/watch?v=Ap_DlSrT-iE&feature=related –

+0

Sau đó, bạn nên so sánh mã của mình với mã đi kèm tại đây: http://www.newthinktank.com/2010/11/python-2 -7-tutorial-pt-13-trang web-scraping /. Sau một chút gọn gàng, tôi thấy rằng nó hoạt động. – Johnsyweb

Trả lời

19

Bạn cần phải nhập khẩu regular expression module trong mã của bạn

import re 
re.compile('<title>(.*)</title>') 
+0

cảm ơn. Bây giờ tôi nhận được một lỗi khác..xin vui lòng xem các chỉnh sửa của tôi –

+3

@ user522962 'trang web = urlopen ('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews') .read' nên là 'trang web = urlopen (' http: // feeds.huffingtonpost.com/huffingtonpost/LatestNews '). read() ' – razpeitia

1

Hiện nay webpage là một tham chiếu đến một hàm. Tôi nghi ngờ bạn đã để lại () sau read

Các vấn đề liên quan