- 论坛徽章:
- 0
|
- from urllib import urlopen
- from urllib import urlencode
- import re
- wd = 'python'
- wd = urlencode({'wd':wd})
- url = "http://www.baidu.com" + wd
- page = urlopen(url).read()
- content = (page.decode('utf-8')).replace('\n', '').replace('\t', '')
- title = re.findall(r'<h3 class="t".*?h3>', content)
- title = [item[item.find('href =')+6:item.find('target=')] for item in title]
- title = [item.replace(' ', '').replace('"', '') for item in title]
- for item in title:
- print item
复制代码 如果我把以上代码一行行粘贴到终端,这个代码就可以运行,但是,如果我直接使用python file.py则提示错误,错误如下:
- Traceback (most recent call last):
- File "url.py", line 8, in <module>
- page = urlopen(url).read()
- File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 87, in urlopen
- return opener.open(url)
- File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 213, in open
- return getattr(self, name)(url)
- File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 350, in open_http
- h.endheaders(data)
- File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1038, in endheaders
- self._send_output(message_body)
- File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 882, in _send_output
- self.send(msg)
- File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 844, in send
- self.connect()
- File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 821, in connect
- self.timeout, self.source_address)
- File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 557, in create_connection
- for res in getaddrinfo(host, port, 0, SOCK_STREAM):
- IOError: [Errno socket error] [Errno 8] nodename nor servname provided, or not known
复制代码
我的python版本是2.7.13
|
|