加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax爬虫来了~

发布时间:2020-12-16 01:50:19 所属栏目:百科 来源:网络整理
导读:最近好忙啊,都没空看python,小代码一段弥补一下我的内疚: from lxml import htmlfrom time import sleepimport requestsimport osls = os.linesepfilename = "OutputFile_2.txt"if os.path.exists(filename): print "ERROR,'%s' already exists!Please nam
最近好忙啊,都没空看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!!'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读