ajax爬虫来了~

前端之家收集整理的这篇文章主要介绍了ajax爬虫来了~前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
最近好忙啊,都没空看python,小代码一段弥补一下我的内疚:
from lxml import html
from time import sleep
import requests
import os

ls = os.linesep
filename = "OutputFile_2.txt"
if os.path.exists(filename):
    print "ERROR,'%s' already exists!Please name the file again~" % filename
fobj = open(filename,'w')

writeline = "Ajax information from Byr English Bar"+ls+ls

headers = {'X-Requested-With': ' XMLHttpRequest'}
page = requests.get(r'http://bbs.byr.cn/board/EnglishBar?_uid=guest',headers=headers)
tree = html.fromstring(page.text)
titles = tree.xpath('//td[@class="title_9"]/a/text()')
authors = tree.xpath('//td[@class="title_12"]/a/text()')
time = tree.xpath('//td[@class="title_10"]/text()')
i = 0
for title in titles:
    writeline += title+ls+">>auther:"+authors[i]+ls+">>Posting time:"+time[i]+ls+ls
    i = i+1

writeline += ls+ls+"*********************function: searching next pages**************************"+ls+ls
for i in range(2,5):
    page = requests.get('http://bbs.byr.cn/board/EnglishBar?p=%d&_uid=guest' % i,headers=headers)
    tree = html.fromstring(page.text)
    titles = tree.xpath('//td[@class="title_9"]/a/text()')
    writeline += "on the page %d,the number of titles is %d.And the top 5 are:" % (i,len(titles))+ls
    for j in range(0,5):
        writeline += titles[j]+ls
    writeline += ls

with open(filename,'wb') as out:
    out.write(writeline.encode('utf-8'))
    
fobj.close() 
print 'Done!Tada!!'

猜你在找的Ajax相关文章