我是比較新的蟒蛇所以這樣的事情不來容易給我。使用的urllib2遍歷網頁內容
我只是通過一個網頁要循環的內容,然後打印每次出現在控制檯窗口中現在,但我顯然有我的循環是錯誤的。
import sys
import re
import urllib2
import urlparse
crawling = tocrawl.pop()
response = urllib2.urlopen(crawling)
msg = response.read()
endDiv = msg.find('</div>')
while endDiv != -1:
endDiv = msg.find('</div>')
startPos = msg.find('class="facultyname">', endDiv)
if startPos != -1:
nextPos = msg.find('.php">', startPos)
endPos = msg.find('</a>', nextPos)
if endPos != -1:
name = msg[nextPos+6:endPos]
print name, " ",
startPos = msg.find('function escramble()')
if startPos != -1:
nextPos = msg.find('b=', startPos)
endPos = msg.find('c', nextPos)
if endPos != -1:
email = msg[nextPos+3:endPos-1]
email = email[:-13] + '@email.com'
print email
endDiv = msg.find('</div>', endPos)
我已經抓住了第一次發生,我只是想循環直到頁面結束並收集剩下的部分。
樣本HTML:
<div id="main-text">
<p class="title">Research Scientists</p>
<div class="space"> </div>
<img src="photos/icons/bastolaicon.jpg" class="faculty" width="53" height="71" alt="Bastola Photo" />
<div class="facultyname">
<strong><a href="people/bastola.php">person1</a>
<br /><em>Post-Doctoral Scientist</em></strong>
<br />
</div>
<div class="facultybody">
Rm. 218A
<br /><em><script type="text/javascript">
<!--
function escramble(){
var a,b,c,d,e,f,g,h,i
a='<a href=\"mai'
b='person1'
c='\">'
a+='lto:'
b+='@'
e='</a>'
f=''
b+='email.com'
g='<img src=\"'
h=''
i='\" alt="Email us." border="0">'
if (f) d=f
else if (h) d=g+h+i
else d=b
document.write(a+b+c+d+e)
}
escramble()
//-->
</script></em>
</div>
<div class="space"> </div>
<img src="photos/icons/person2icon.jpg" class="faculty" width="53" height="71" alt="person2 Photo" />
<div class="facultyname">
<strong><a href="people/person2.shtml">person2</a>
<br /><em>Assistant Research Scientist</em></strong>
<br />
</div>
<div class="facultybody">
Rm. 227
<br />(850) 645-1253
<br /><em><script type="text/javascript">
<!--
function escramble(){
var a,b,c,d,e,f,g,h,i
a='<a href=\"mai'
b='person2'
c='\">'
a+='lto:'
b+='@'
e='</a>'
f=''
b+='email.com'
g='<img src=\"'
h=''
i='\" alt="Email us." border="0">'
if (f) d=f
else if (h) d=g+h+i
else d=b
document.write(a+b+c+d+e)
}
escramble()
//-->
</script></em>
</div>
<div class="spacer"> </div>
如果你想抓取文件的數據和元素,你最好的拍攝將是[BeautifulSoup](http:// www。 crummy.com/software/BeautifulSoup/) – nvlass
你有一小組示例HTML嗎?我有一種感覺,這將是更適合於'beautifulsoup'或'lxml.html' ......(雖然它看起來像你想找到一個JS機能的研究範圍內的東西) –
我不想讓它太複雜。我只是想在這些職位之間找到數據的頁面。我已經抓住了第一次出現,我只想循環到頁面結束並收集剩下的內容。 – frankV