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!!'

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值