Python爬虫爬取OA幸运飞艇平台获取数据

安装BeautifulSoup以及requests

打开window 的cmd窗口输入命令pip install requests 执行安装,等待他安装完成就可以了

BeautifulSoup库也是同样的方法

我使用的编译器的是sublime text 3,觉得是挺好用的一个编译软件

其他工具: Chrome浏览器

Python版本: Python3.6

运行平台: Windows

1、首先我们搜索OA幸运飞艇平台排行榜:【×××。com/h5】企 娥:217 1793 408
Python爬虫爬取OA幸运飞艇平台获取数据
获取网页的代码:

[python] view plain copy
def getHTMLText(url,k):
try:
if(k==0):
a={}
else:
a={'offset':k}
r = requests.get(url,params=a,headers={'User-Agent': 'Mozilla/4.0'})
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
print("Failed!")
经过观察其中因为每一页的网址其offset都不相同,故只要改变offset=k便可获取每一页的信息

通过main函数以改变URL:

[python] view plain copy
def main():
basicurl='×××。com/h5'
k=0
while k<=100:
html=getHTMLText(basicurl,k)
k+=10
getname(html)
通过BeautifulSoup的方法层层获取标签中的信息,并for循环输出

[python] view plain copy
def getname(html):
soup = BeautifulSoup(html, "html.parser")
paihangList=soup.find('dl',attrs={'class':'board-wrapper'})
mov=[]
actor=[]
for movlist in paihangList.find_all('dd'):
movitem=movlist.find('div',attrs={'class':'movie-item-info'})
movname=movitem.find('p',attrs={'class':'name'}).getText()
actors=movlist.find('div',attrs={'class':'board-item-main'})
actorname=actors.find('p',attrs={'class':'star'}).getText()
b=actorname.replace('\n','')
c=b.replace(' ','')
actor.append(c)
mov.append(movname)
mode= "{0:<30}\t{1:<50}"
for i,j in zip(mov,actor):
print(mode.format(i,j,chr(12288)))

猜你喜欢

转载自blog.51cto.com/13833489/2132578